﻿var ip = '';
var port=0;
var user = '';
var pswd = '';
var avId = '';

var win_count=0;		//视频窗口总数
var win_hwnd_list=null;
var toolindex  = -1;
var timer = null;
var g_servertitle = '';

var ocxVer = [0,0,0];
var g_focusChangeIndex = 0;
var g_setfocusIndex = 0;

var g_pvaocxdownloadparam = "";
var g_pvaocxdownloadtype = 0;
var g_realtimestreamparam = "";
var g_playbackstreamparam = "";
var allowEvent=true;
var g_roundid = 0;
var g_roundtimer = null;
var g_roundlistchange = false;
var g_loginfo = "";
var g_camerainfo = null;
var tree_target = null;
var tree_target_record = null;
var openimg="images/camera-16.png";
var closeimg="images/camera16.png";
var selectrealdrawObjectID = -1;
var bselectrealdrawObjectID = 0;
var setting = {
	check: {
			enable: false
		},
	callback:{
		onClick:function(event, treeid ,treeNode,clickFlag)
		{
			//tvwCamera_dblclick(treeNode);
		},
		onDblClick:function(event, treeid ,treeNode){
			if(treeNode==null||!treeNode.data||treeNode.isaudio)
				return;

			tvwCamera_dblclick(treeNode);
		},
		onRightClick: function(event, treeid ,treeNode){
			if(treeNode==null||!treeNode.data||treeNode.isaudio)
				return;
			tree_target=treeNode;
			if(tree_target.isrecording)
			{
				$('#menu_tree1').menu('show', {
					left: event.pageX,
					top: event.pageY
				});
			}
			else
			{
				$('#menu_tree').menu('show', {
					left: event.pageX,
					top: event.pageY
				});
			}
			
		}
		
	}
};

//var funweb = function(){};


$(function()
{   
	var http = GetHttpPath();
	var pix = document.getElementById("pixwin");
	if(!pix)
	{
		var div = document.getElementById("win_pixwin");
		div.innerHTML = "<object id='pixwin' type='applicatin/x-firebreath' width='100%' height='100%'><param name='onload' value='pluginLoaded'/>  </object>";
		pix = document.getElementById("pixwin");
	}
	var needupdata = 0;
	var strjson = readFileJSON();
	if(!pix || !pixwin.version){
		needupdata = 1; //没有安装
	}
	else{
		prints("strjson = " + strjson)
		if(pixwin.IsUpgradeVersion){
			if(IsUpgradeVersion(strjson))
			{
				needupdata = 3;//配置文件要求升级（本地版本低或强制回退）
			}
		}
		else{
			needupdata = 2; //没有升级接口 说明版本低
		}	
	}
	
	if(needupdata)
	{
		if(confirm('检测到新版本，是否更新'))
		{
			downloadvideplayer();
			//alert('选择了是');
		}
		else
		{
			prints("放弃了本次升级");
			//alert('选择了否'); 
		}
		
	}


	$('#inputFile').click(function(){
		var param = {
		"flags":0x0006,   
		"filter":"All Files (*.*)|*.*||"
		}
		var fileValue =  OpenSaveFileDlg(1,JSON.stringify(param));
		fileValue = JSON.parse(fileValue);
		if(fileValue)
			$('#txt_filepath').attr('value',fileValue[0].filename);
	});

	$('#inputFile2').click(function(){
		var param = {
		"flags":0x0006,   
		"filter":"All Files (*.*)|*.*||"
		}
		var fileValue =  OpenSaveFileDlg(1,JSON.stringify(param));
		fileValue = JSON.parse(fileValue);
		if(fileValue)
			$('#txt_filepath2').attr('value',fileValue[0].filename);
	});
	

	////////////窗口云台///////////////
	
	$('#btn_ptz_right').mousedown(function () {
		btn_ptz_mousedown(0);
	});
	$('#btn_ptz_rightup').mousedown(function () {
		btn_ptz_mousedown(1);
	});	
	$('#btn_ptz_up').mousedown(function () {
		btn_ptz_mousedown(2);
	});	
	$('#btn_ptz_leftup').mousedown(function () {
		btn_ptz_mousedown(3);
	});
	$('#btn_ptz_left').mousedown(function () {
		btn_ptz_mousedown(4);
	});
	$('#btn_ptz_leftdown').mousedown(function () {
		btn_ptz_mousedown(5);
	});
	$('#btn_ptz_down').mousedown(function () {
		btn_ptz_mousedown(6);
	});
	$('#btn_ptz_rightdown').mousedown(function () {
		btn_ptz_mousedown(7);
	});

	$('#btn_ptz_light1').mousedown(function () {
		btn_ptz_mousedown(10,true);
	});
	$('#btn_ptz_light2').mousedown(function () {
		btn_ptz_mousedown(10);
	});
	$('#btn_ptz_zoom1').mousedown(function () {
		btn_ptz_mousedown(11,true);
	});
	$('#btn_ptz_zoom2').mousedown(function () {
		btn_ptz_mousedown(11);
	});
	$('#btn_ptz_focus1').mousedown(function () {
		btn_ptz_mousedown(12,true);
	});
	$('#btn_ptz_focus2').mousedown(function () {
		btn_ptz_mousedown(12);
	});

	$('#btn_ptz_view').mousedown(function () {
		btn_ptz_mousedown(13);
	});
	$('#btn_ptz_setview').mousedown(function () {
		btn_ptz_mousedown(14);
	});


	$('#btn_ptz_right').mouseup(function () {
		btn_ptz_mouseup(0);
	});
	$('#btn_ptz_rightup').mouseup(function () {
		btn_ptz_mouseup(1);
	});	
	$('#btn_ptz_up').mouseup(function () {
		btn_ptz_mouseup(2);
	});	
	$('#btn_ptz_leftup').mouseup(function () {
		btn_ptz_mouseup(3);
	});
	$('#btn_ptz_left').mouseup(function () {
		btn_ptz_mouseup(4);
	});
	$('#btn_ptz_leftdown').mouseup(function () {
		btn_ptz_mouseup(5);
	});
	$('#btn_ptz_down').mouseup(function () {
		btn_ptz_mouseup(6);
	});
	$('#btn_ptz_rightdown').mouseup(function () {
		btn_ptz_mouseup(7);
	});

	$('#btn_ptz_light1').mouseup(function () {
		btn_ptz_mouseup(10);
	});
	$('#btn_ptz_light2').mouseup(function () {
		btn_ptz_mouseup(10);
	});
	$('#btn_ptz_zoom1').mouseup(function () {
		btn_ptz_mouseup(11);
	});
	$('#btn_ptz_zoom2').mouseup(function () {
		btn_ptz_mouseup(11);
	});
	$('#btn_ptz_focus1').mouseup(function () {
		btn_ptz_mouseup(12);
	});
	$('#btn_ptz_focus2').mouseup(function () {
		btn_ptz_mouseup(12);
	});
	$('#btn_ptz_ptzlock').mouseup(function () {
		btn_ptz_ptzlock_click();
	});





	//////////视频颜色/////////
	$('#btn_getcolor').click(function(){
		btn_getcolor_click();
	});	
	$('#btn_setcolor').click(function(){
		btn_setcolor_click();
	});		
	
	/////////////窗口布局/////////
	$('#btn_win_one').click(function(){
		btn_win_click(1);
	});
	$('#btn_win_four').click(function(){
		btn_win_click(4);
	});	
	$('#btn_win_nine').click(function(){
		btn_win_click(9);
	});
	$('#btn_win_sixteen').click(function(){
		btn_win_click(16);
	});

	$('#btn_win_1A5').click(function(){
		btn_win_click(15);
	});
	$('#btn_win_1A7').click(function(){
		btn_win_click(17);
	});	
	$('#btn_win_1A9').click(function(){
		btn_win_click(19);
	});

	$('#btn_win_mxn').click(function(){
		btn_win_mxn_click();
	});

	$('#btn_win_fullscreen').click(function(){
		btn_win_fullscreen_click();

	});

	$('#chk_windowSpace').change(function(){
		windowSpace_change();
	});

	$('#chk_windowSwitch').change(function(){
		windowSwitch_change();

	});


	$('#btn_Interspace').click(function(){
		btn_Interspace_click();
	});

	$('#btn_FocusBorder').click(function(){
		btn_FocusBorder_click();
	});

	$('#btn_VideoMargin').click(function(){
		btn_VideoMargin_click();
	});

	$('#btn_isFoces').click(function(){
		btn_isFoces_click();
	});

	$('#btn_setFocus').click(function(){
		btn_setFocus_click();
	});

	$('#btn_isHaveMax').click(function(){
		btn_isHaveMax_click();
	});

	




	$('#chk_loadingGif').change(function(){
		loadingGif_change();
	});

	$('#chk_ptzEnable').change(function(){
		ptzEnable_change();
	});

	$('#chk_HandilyCloseDZoom').change(function(){
		HandilyCloseDZoom_change();
	});

	$('#chk_EnablePTZDblclk').change(function(){
		EnablePTZDblclk_change();
	});

	$('#chk_EnablePIP').change(function(){
		EnablePIP_change();
	});
	$('#chk_useptzand3dptz').change(function(){
		useptzand3dptz_change();
	});


	$('#chk_EnableDES').change(function(){
		EnableDES_change();
	});
	
	
	$('#btn_OSD').click(function(){
		btn_OSD_click(1);
	});
	$('#btn_OSDSet').click(function(){
		btn_OSD_click(2);
	});
	$('#btn_OSDDel').click(function(){
		btn_OSD_click(0);
	});

	$('#btn_SetHWConfig').click(function(){
		btn_SetHWConfig_click();
	});


	$('#btn_ssnpvg_play').click(function(){
		btn_ssnpvg_play_click();
	});
	$('#btn_ssnrtsp_play').click(function(){
		btn_ssnrtsp_play_click();
	});

	/////////////播放/////////
	$('#btn_stream_play').click(function(){
		btn_stream_play_click();
	});


	$('#btn_record_play').click(function(){
		btn_record_play_click();
	});

	$('#btn_file_play').click(function(){
		btn_file_play_click();
	});

	$('#btn_pfs_download').click(function(){
		btn_pfs_download_click();
	});
	$('#btn_pfs_upload').click(function(){
		btn_pfs_upload_click();
	});
	$('#btn_pfs_delete').click(function(){
		btn_pfs_delete_click();
	});

	$('#btn_http_download').click(function(){
		btn_http_download_click();
	});
	

	

	$('#btn_sipstream_play').click(function(){
		btn_sipstream_play_click();
	});

	$('#btn_siprecord_play').click(function(){
		btn_siprecord_play_click();
	});

	$('#btn_siprecord_download').click(function(){
		btn_siprecord_download_click();
	});

	$('#btn_closeall').click(function(){
		btn_closeall_click();
	});

	$('#btn_record_download').click(function(){
		btn_record_download_click();
	});
	$('#btn_record_query').click(function(){
		btn_record_query_click();
	});

	$('#btn_addto').click(function(){
		btn_addto_click();
	});


	$('.cam-id').live('click', function(){

		//exchangeocx();

		var streaminfo = this.getAttribute("data-value")
		var index = GetUsefulIndex();
		playstreamEx(index, JSON.parse(streaminfo));
	});

	$('.cam-pro').live('click', function(){
		var tr = this.parentNode.parentNode;
		$(tr).remove();
		g_roundlistchange = true;
	});


	$('#btn_rofsstream_play').click(function(){
		btn_rofsstream_play_click();
	});


	$('#btn_rofsrecord_play').click(function(){
		btn_rofsrecord_play_click();
	});

	$('#btn_rofsrecord_download').click(function(){
		btn_rofsrecord_download_click();
	});
	$('#btn_rofsrecord_query').click(function(){
		btn_rofsrecord_query_click();
	});


	////////轮巡//////////

	$('#btn_roundstart').click(function(){
		btn_roundstart_click();
	});

	$('#btn_roundend').click(function(){
		btn_roundend();
	});

	
	/////////通道列举///////////

	$('#btn_listobject').click(function(){
		btn_listobject_click();
	});

	$('#btn_updateobject').click(function(){
		btn_updateobject_click();
	});
	
	$('#menutree_opencamera').click(function(){
		tvwCamera_dblclick(tree_target)
	});

	$('#menutree_queryrecord0').click(function(){
		menutree_queryrecord(false);
	});
	$('#menutree_queryrecord1').click(function(){
		menutree_queryrecord(true);
	});

	$('#menutree_StartServerRecord').click(function(){
		menutree_ServerRecord(true)
	});
	$('#menutree_StopServerRecord').click(function(){
		menutree_ServerRecord(false)
	});


	$('#menutree_closeall').click(function(){
		btn_closeall_click();
	});

	$('#query_ok').click(function(){
		btn_query_ok_click();
	});

	$('#query_play').click(function(){
		btn_query_playclick();
	});

	$('#query_download').click(function(){
		btn_query_download_click();
	});
	//realdraw
	$('#btn_openrealdraw').click(function(){
		btn_openrealdraw_click();
	});
	$('#btn_closerealdraw').click(function(){
		btn_closerealdraw_click();
	});
	$('#btn_realdrawObject').click(function(){
		btn_realdrawObject_click();
	});
	$('#btn_removerealdrawObject').click(function(){
		btn_removerealdrawObject_click();
	});

	$('#chk_EnableWatermark').change(function(){
		var enable = GetEnableWatermark();
		EnableWatermark(enable) ;
		param = {
				"id"      : 21,
				"text"    : "增加水印",
				"gray"    : !enable
 			};
 		param =	JSON.stringify(param);
 		for(var index=0; index<win_hwnd_list.length;index++){
			SetJsonMenu(index, param);
		}
	});

	$('#chk_EnableRcdTimerShaft').change(function(){
		var enable = GetEnableRcdTimerShaft();
		EnableRcdTimerShaft(enable) ;		
	});
	

	$('.record-id').live('click', function(){
		var record = getRecordPathbytr(this);
		var index = GetUsefulIndex();
		playstreamEx(index, record);
	});

	$('.record-p').live('click', function(){
		var record = getRecordPathbytr(this);
		var index = GetUsefulIndex();
		playstreamEx(index, record);
	});

	$('.record-d').live('click', function(){
		var record = getRecordPathbytr(this);
		record_download(record,0);
	});

	handleEvent(attachEventEx);

	$(window).resize(function(){

	});

	
	$(window).unload( function (){
		//btn_closeall_click();
	});
	
	window.onbeforeunload=function(){
		win_beforeunload_main();
	};

	  document.onkeydown=function(event){
	 	var e = event || window.event || arguments.callee.caller.arguments[0];
	 		if(e && e.keyCode==32){ //   
	 			prints("key space down by web");//要做的事情
	 		}
	// 		if(e && e.keyCode==113){ // 按 F2 
	// 		//要做的事情
	// 		}            
	// 		if(e && e.keyCode==13){ // enter 键
	// 			//要做的事情
	// 		}
	 }; 
	 init_play();
});
function exchangeocx()
{
	var div = document.getElementById("win_pixwin");
	pix = document.getElementById("pixwin");
	if(pix){
		btn_closeall_click();
		div.innerHTML = ""
	}
	//GetFocesIndex();
	//div.innerHTML = "<object id='pixwin' type='applicatin/x-firebreath' width='100%' height='100%'><param name='onload' value='pluginLoaded'/></object>"
	div.innerHTML = "<object id='pixwin' width='100%' height='100%' standby='Waiting...' classid='clsid:294EEBEC-7677-4EBA-B2D7-3FD669FBF2A2' ></object>"
	pix = document.getElementById("pixwin");
	//SetLayout(1);
	win_hwnd_init();
}

function attachEventEx(element, evtstr, evtfun){
	
	if (window.attachEvent) { 
		element.attachEvent("on"+evtstr, evtfun); 
	} else if (window.addEventListener) {
		element.addEventListener(evtstr, evtfun, false);   
	} 
	else{
		element["on"+evtstr] = evtfun;
	}
}


function detachEventEx(element, evtstr, evtfun){
	
	if (window.detachEvent) { 
		element.detachEvent("on"+evtstr, evtfun); 
	} else if (window.removeEventListener) {
		element.removeEventListener(evtstr, evtfun, false);   
	} 
	else{
		element["on"+evtstr] = null;
	}
}


function handleEvent( handleMethod)
{
	/////////////事件/////////
	var pix = document.getElementById('pixwin');
	handleMethod(pix, 'WebDialogEvent',pixwin_WebDialogEvent);	

	handleMethod(pix, 'PTZContorlEvent',pixwin_PTZContorlEvent );	
	handleMethod(pix, 'FocusChange',pixwin_FocusChange);	
	handleMethod(pix, 'WndClick',pixwin_WndClick);	
	
	handleMethod(pix, 'LButtonDblClick',pixwin_LButtonDblClick)
	handleMethod(pix, 'WndDClik',pixwin_WndDClik);	
	handleMethod(pix, 'SwitchWindow',pixwin_SwitchWindow);	
	handleMethod(pix, 'UnexecutedSwitchWindow',pixwin_UnexecutedSwitchWindow);	
	handleMethod(pix, 'MouseEnterWindow',pixwin_MouseEnterWindow);	
	handleMethod(pix, 'MouseLeaveControlEx',pixwin_MouseLeaveControlEx);	
	handleMethod(pix, 'MouseMoveWindow',pixwin_MouseMoveWindow);	
	handleMethod(pix, 'MouseLeaveControl',pixwin_MouseLeaveControl);
	handleMethod(pix, 'LayoutChange',pixwin_LayoutChange);	
	handleMethod(pix, 'FullScreen',pixwin_FullScreen);	
	handleMethod(pix, 'ExitFullScreen',pixwin_ExitFullScreen);	
	handleMethod(pix, 'SizeChanged',pixwin_SizeChanged);	
	handleMethod(pix, 'MouseDown',pixwin_MouseDown);	
	handleMethod(pix, 'MouseUp',pixwin_MouseUp);	
	handleMethod(pix, 'MouseMove',pixwin_MouseMove);	
	handleMethod(pix, 'MouseWheelEvent',pixwin_MouseWheelEvent);	
	handleMethod(pix, 'PlayBackStartOrEnd',pixwin_PlayBackStartOrEnd);	
	handleMethod(pix, 'ExpandScreen',pixwin_ExpandScreen);//on
	handleMethod(pix, 'StreamTimeout',pixwin_StreamTimeout);	
	handleMethod(pix, 'DecoderTimeout',pixwin_DecoderTimeout );	
	handleMethod(pix, 'DRcdFileSplitEvent',pixwin_DRcdFileSplitEvent );	
	handleMethod(pix, 'DownLoadPercent',pixwin_DownLoadPercent );	
	handleMethod(pix, 'OcxNotifyEvent',pixwin_OcxNotifyEvent );	
	handleMethod(pix, 'CommonEvent',pixwin_CommonEvent );


}


/////////////事件响应函数/////////
function pixwin_WebDialogEvent(id, elementID, elementValue)
{
	id=parseInt(id);
	if(elementValue == "window.close"){
		for(var i=0; i<win_hwnd_list.length; i++){
			if(win_hwnd_list[i].webid == id){
				win_hwnd_list[i].webid = 0;
				break;
			}
		}
	}
	prints("WebDialogEvent("+id+","+elementID+","+elementValue+")");
}	

function pixwin_PTZContorlEvent(index, cmd, enable, trigger)
{
	index = parseInt(index);
	cmd=parseInt(cmd);
	enable=parseInt(enable);
	trigger = parseInt(trigger);
	prints("PTZContorlEvent("+index+","+cmd+","+enable+","+trigger+")");
	return;
	if(enable){
		printlog("PTZContorlEvent("+index+","+cmd+","+enable+","+trigger+")");
	}
	else{
		prints("PTZContorlEvent("+index+","+cmd+","+enable+","+trigger+")");
	}
}	

function pixwin_FocusChange(old, newindex)
{
	newindex = parseInt(newindex);
	g_focusChangeIndex = newindex;
	//prints("FocusChange("+old+","+newindex+")");
}	

function pixwin_WndClick(index, x, y)
{
	printlog("WndClick("+index+","+x+","+y+")");
}	

function pixwin_LButtonDblClick(index, flag, x,y, res)
{
	prints("LButtonDblClick("+index+","+flag+","+x+","+y+","+res+")");
}
function pixwin_WndDClik(index, x, y)
{
	if(win_hwnd_list == null){
		return;
	}
	index = parseInt(index);
	if(GetHandilyCloseDZoom()&&win_hwnd_list[index].zoom)
	{
		var status = GetZoomStatus(index);//GetAllZoomStatus();
		if(status == 0){
			SetMenuZoomStatus(index, false);
		}
	}
	
	AdjustToolbarItem(index);
	printlog("WndDClik("+index+","+x+","+y+")");
}	

function pixwin_SwitchWindow(srcpos, dstpos)
{
	srcpos = parseInt(srcpos);
	dstpos = parseInt(dstpos);
	//printlog("SwitchWindow("+srcpos+","+dstpos+")");
	var param = win_hwnd_list[srcpos];
	win_hwnd_list[srcpos] = win_hwnd_list[dstpos];
	win_hwnd_list[dstpos] = param;
	toolindex = srcpos;
	if(toolindex!=-1){
		//AdjustToolbarItem(toolindex);
	}
}	

function pixwin_UnexecutedSwitchWindow(srcpos, dstpos)
{
	prints("UnexecutedSwitchWindow("+srcpos+","+dstpos+")");
}	

function pixwin_MouseEnterWindow(index, x, y)
{
	//prints("MouseEnterWindow  "+index);
	index = parseInt(index);
	if(toolindex>-1 && ocxVer[0]>1){
		ShowWindowToolbar(toolindex, false);
	}

	ShowWindowToolbar(index, true);
	//AdjustToolbarItem(index);
	toolindex = index;
}	

function pixwin_MouseLeaveControlEx(index, x, y)
{

	if(ocxVer[0]==2 && toolindex>-1){
		ShowWindowToolbar(toolindex, false);
	}
	toolindex = 0;
	//prints("MouseLeaveControlEx("+index+")");
}	

function pixwin_MouseMoveWindow(index, x, y)
{
	printlog("MouseMoveWindow("+index+","+x+","+y+")");
}	

function pixwin_MouseLeaveControl(index)
{
	printlog("MouseLeaveControl("+index+")");
}	

function pixwin_LayoutChange(oldcount, newcount)
{
	if(win_hwnd_list==null){
		return;
	}
		
	// for(var i=0; i<win_hwnd_list.length; i++){
	// 	AdjustToolbarItem(i);
	// }
	prints("LayoutChange("+oldcount+","+newcount+")");
}	

function pixwin_FullScreen()
{
	prints("FullScreen()");
}	

function pixwin_ExitFullScreen()
{
	prints("ExitFullScreen()");
}	

function pixwin_SizeChanged(oldwidth, oldheight, newwidth, newheight)
{
	if(win_hwnd_list==null){
		return;
	}

	for(var i=0; i<win_hwnd_list.length; i++){
		AdjustToolbarItem(i);
	}
	//prints("SizeChanged("+oldwidth+","+oldheight+","+newwidth+","+newheight+")");
}	

function pixwin_MouseDown(index, flag, x, y)
{
	printlog("MouseDown("+index+","+flag+","+x+","+y+")");
}	

function pixwin_MouseUp(index, flag, x, y)
{
	prints("MouseUp("+index+","+flag+","+x+","+y+")");
}	

function pixwin_MouseMove(index, flag, x, y)
{
	printlog("MouseMove("+index+","+flag+","+x+","+y+")");
}	

function pixwin_OcxNotifyEvent(type, strinfo)
{
	printlog("OcxNotifyEvent("+type+","+strinfo+")");
}	


function pixwin_MouseWheelEvent(index, data, x, y)
{
	printlog("MouseWheelEvent("+index+","+data+","+x+","+y+")");
}	

function pixwin_PlayBackStartOrEnd(index, flag)
{
	printlog("PlayBackStartOrEnd("+index+","+flag+")");
}	

function pixwin_ExpandScreen(monitorInfo, newMonitorInfo)
{
	printlog("ExpandScreen("+monitorInfo+","+newMonitorInfo+")");
}	

function pixwin_StreamTimeout(index, id, mode)
{
	printlog("StreamTimeout("+index+","+id+","+mode+")");
}	

function pixwin_DecoderTimeout(index, id, mode)
{
	printlog("DecoderTimeout("+index+","+id+","+mode+")");
}	

function pixwin_DRcdFileSplitEvent (id, brFileName, brReserved)
{
	printlog("DRcdFileSplitEvent("+id+","+brFileName+","+brReserved+")");
}	

function pixwin_DownLoadPercent(id, percent)
{
	printlog("DownLoadPercent("+id+","+percent+")");
}


//typeEvent = 201 
function pixwin_CommonEvent(typeEvent, eventInfo, reserved)
{
	typeEvent = parseInt(typeEvent);
	prints("CommonEvent("+typeEvent+", "+eventInfo+", "+reserved+")");
	if (typeEvent == 202)
	{
		var info = JSON.parse(eventInfo);
		if(info["select"] == 1){
		selectrealdrawObjectID = info["id"];
			bselectrealdrawObjectID = 1;
		}else{
			selectrealdrawObjectID = -1;
			bselectrealdrawObjectID = 0;
		}
	}
}

function commonEventCB(typeEvent, eventInfo,  userParam, reserved)
{
	prints("commonEventCB("+typeEvent+", "+eventInfo+", "+userParam+", "+reserved+")");
}


/////////加载/////////
function win_beforeunload_main()
{
	if(!allowEvent){
		prints("win_beforeunload_main return");
		return;
	}
	handleEvent(detachEventEx);
	if(timer != null){
		clearInterval(timer);
		timer = null;
	}
	if(!win_hwnd_list)
		return;
	for(var i=0; i<win_hwnd_list.length; i++){
		StopStream(i);
	}
	
}


function win_load_main()
{

	if(!pixwin || !pixwin.version)
	{
		return;
	}
		

	var Ver = GetVersion();
	ocxVer = Ver.match(/\d+/g);
	prints("安装包版本"+GetLocalRegInfo());

	GetMacString();

	if(ocxVer[0] == 2){
		DownloadToolbarImage(GetHttpPath()+"/toolbar");
	}

	RegCommonEventCallback(commonEventCB,0);
	

	SetLayout(1);
	win_hwnd_init();


	var date=new Date();
	var begin=date.getFullYear().toString() + "-" + (date.getMonth()+1).toString() + "-"+date.getDate().toString();
	var end=date.getFullYear().toString() + "-" + (date.getMonth()+1).toString()+ "-"+date.getDate().toString();
	$('#rofs_datetime_begin').datebox('setValue',begin);
	$('#rofs_datetime_end').datebox('setValue',end);
	begin=(date.getHours()-1).toString() + ":" + date.getMinutes().toString() + ":" + date.getSeconds().toString()+".000";
	end=date.getHours() + ":" + date.getMinutes().toString() + ":" + date.getSeconds().toString()+".000";
	$('#rofs_time_begin').attr('value',begin);
	$('#rofs_time_end').attr('value',end);

	//document.getElementsByName("fileType")[0].checked=true;
	//document.getElementsByName("sipVodtype")[0].checked=true;
	//document.getElementsByName("uploadfileType")[0].checked=true;
	//document.getElementsByName("servertype")[0].checked=true;
	//document.getElementsByName("rofsservertype")[1].checked=true;
	

	try{
		SetHandilyCloseDZoom(true);
		var bstatus = GetHandilyCloseDZoom();
		$('#chk_HandilyCloseDZoom').attr('checked', bstatus);
	}
	catch (e){
		$('#chk_HandilyCloseDZoom').attr('checked', false);
	}
	var bstatus = GetEnablePTZDblclk();
	$('#chk_EnablePTZDblclk').attr('checked', bstatus);
	$('#chk_EnablePIP').attr('checked', false);
	$('#chk_useptzand3dptz').attr('checked', false);
	$('#chk_fastdownload').attr('checked', true);
	$('#chk_track').attr('checked', false);

	$('#chk_EnableWatermark').attr('checked', true);
	EnableWatermark(true);
	

	$('#chk_EnableRcdTimerShaft').attr('checked', true);
	EnableRcdTimerShaft(true);

	try{
		var ret = GetHWDecoderConfig();
		ret = JSON.parse(ret);
		if(ret){
			ret = ret["hwdecoder"];
			if(ret["support"]==1){
				//document.getElementsByName("hwdecoder")[0].checked=true;
				prints("硬解设置: "+ret["mode"]);
			}
			else{
				prints("计算机不支持硬解");
				//document.getElementsByName("hwdecoder")[2].checked=true;
			}
		}
	}
	catch (e){
		prints("控件不支持硬解");
		//document.getElementsByName("hwdecoder")[2].checked=true;
	}

	//updatestreamspeed();

	//try{
		//document.getElementById("btn_roundend").style.visibility="hidden";
	//}
	//catch (e){}
	/*
	if(timer == null){
		timer = setInterval(function() {
				for(var i=0; i<win_count; i++){
					if(win_hwnd_list[i].showToolbar){
						UpdateToolbar(i);
					}
				}
			},
			500
			);
	}
	*/
	
	GetRegistryInfo("计算机\\HKEY_LOCAL_MACHINE\\SOFTWARE\\Wow6432Node\\NetPosa\\NP PVA PLUGINS\\PVGSDK");
}



//////////布局//////////////


function win_hwnd_init()
{
	var win_count_old = win_count;
	win_count = GetWindowCount();
	if(win_count_old < win_count){
		loadingGif_change();
		}
	var layout = GetLayout();
	if(win_hwnd_list==null){
		win_hwnd_list=new Array();
		// setInterval(function()
		// {
		// 	var mem = GetMemory();
		// 	prints("cpustatus = "+ mem);
		// },
		// 2000);

		CreateMenu(-1);
		
	}
	
	if(win_hwnd_list.length<win_count)
	{
		for(var i=win_hwnd_list.length;i<win_count;i++)
		{
			var row={};

			row["type"]=-1;  	//文件、实时流、录像、PFS、国标实时流、国标录像，0、1、2、3、4、5；
			row["menu"] = -1;
			row["toolbar"] = -1;
			row["zoom"] = false;
			row["ptz"] = false;
			row["ptz3d"] = false;
			row["showToolbar"] = false;
			row["timerToolbar"] = null;
			row["toolbarTop"] = [];
			row["toolbarBottom"] = [];
			row["path"] = {};
			row["dur"] = 0;
			row["seek"] = -1;
			row["seektimes"] = 0;
			//row["maxdtime"] = 1.0;
			row["bpause"] = false;
			row["brange"] = false;
			row["webid"] = 0;
			row["imageexist"] = false;
			row["audiomode"] = 0;
			row["treenode"] = null;
			row["reverse"] = false;
			win_hwnd_list.push(row);
			//CreateMenu(i);
			CreateWindowToolbar(i)
		}
	}
}


function btn_win_click(layout)
{
	var beforewincount = GetWindowCount();
	var ret = SetLayout(layout);
	if(ret == 0){
		win_hwnd_init();
		var currentwincount = GetWindowCount();
		if (currentwincount < beforewincount)
			g_setfocusIndex = 0;
		g_focusChangeIndex = 0;
	}
}

function btn_win_mxn_click()
{
	var m =$('#txt_layout_m').attr('value');
	var n =$('#txt_layout_n').attr('value');
	var dis =$('#txt_layout_dis').attr('value');
	var err = SetLayoutEx(101, m, n, dis);
	if(err == 0){
		win_hwnd_init();	
	}
	else{
		alert('mXn分屏错误'+err);
	}
}


function btn_win_fullscreen_click()
{
	if(!IsFullScreen()){
		SetFullScreen(true);
	}
}

function windowSpace_change()
{
	var bEnable = false;
	if($('#chk_windowSpace').attr('checked')){
		bEnable=true;
	}
	EnableWindowSpace(bEnable);

}
function windowSwitch_change()
{
	var bEnable = false;
	if($('#chk_windowSwitch').attr('checked')){
		bEnable=true;
	}
	EnableWindowSwitch(bEnable);
}

function loadingGif_change()
{
	var bEnable = false;
	if($('#chk_loadingGif').attr('checked')){
		bEnable=true;
	}

	for(var i=0; i<win_count; i++){
		var ret = EnableLoadingGif(bEnable, i);
	}
}

function EnableDES_change()
{
	var bEnable = false;
	if($('#chk_EnableDES').attr('checked')){
		bEnable=true;
		alert("输入路径信息需加密~")
	}

	
	var ret = EnableDES(bEnable);
}





function btn_Interspace_click()
{
	var r = parseInt($('#txt_color_R').attr('value'));
	var g = parseInt($('#txt_color_G').attr('value'));
	var b = parseInt($('#txt_color_B').attr('value'));
	return SetInterspaceColor(r, g, b);
}
function btn_FocusBorder_click()
{
	var r = parseInt($('#txt_color_R').attr('value'));
	var g = parseInt($('#txt_color_G').attr('value'));
	var b = parseInt($('#txt_color_B').attr('value'));
	return SetFocusColor(r, g, b);
}
function btn_VideoMargin_click()
{
	var r = parseInt($('#txt_color_R').attr('value'));
	var g = parseInt($('#txt_color_G').attr('value'));
	var b = parseInt($('#txt_color_B').attr('value'));
	return SetVideoMarginColor(r, g, b);
}

function btn_isFoces_click()
{
	var index = parseInt($('#txt_window_index').attr('value'));
	var ret = IsFocusWindow(index);
	if(ret){
		alert("窗口 "+index+" 是焦点窗口");
	}
	else{
		alert("窗口 "+index+" 不是焦点窗口");
	}
}
function btn_setFocus_click()
{
	var index = parseInt($('#txt_window_index').attr('value'));
	SetFocusWindow(index);
}

function btn_isHaveMax_click()
{
	var ret = IsHaveMaximizeWindow()
	if(ret){
		alert("有最大化窗口");
	}
	else{
		alert("无最大化窗口");
	}
}

//////////视频颜色//////////////
function btn_getcolor_click()
{
	var index=GetFocesIndex();
	var info=GetColorAttribute(index);
	info = JSON.parse(info);

	$('#txt_brightness').attr('value',info.bright);
	$('#txt_contrast').attr('value',info.contrast);
	$('#txt_saturation').attr('value',info.saturation);
	$('#txt_hue').attr('value',info.hue);
	
}

function btn_setcolor_click()
{
	var index=GetFocesIndex();
	var brightness=parseInt($('#txt_brightness').attr('value'));
	var contrast=parseInt($('#txt_contrast').attr('value'));
	var saturation=parseInt($('#txt_saturation').attr('value'));
	var hue=parseInt($('#txt_hue').attr('value'));
	
	return SetColorAttribute(index,brightness,contrast,saturation,hue);
	
}



function btn_OSD_click(type)
{
	var index = GetFocesIndex();
	SetOsd(index,type);
}


function btn_SetHWConfig_click()
{
	SetHWDecoderConfig("null", 75, 75);
	prints("设置硬解GPU使用率75%，显存使用率75%")
}


/////////PVG流播放////////////////
function GetUsefulIndex()
{
	//return GetFocesIndex();

	if(IsHaveMaximizeWindow())
	{
		return GetFocesIndex();
	}

	var index = g_focusChangeIndex;
	if( g_focusChangeIndex != g_setfocusIndex){
		 g_focusChangeIndex = g_setfocusIndex;
		return index;
	}

	index = g_setfocusIndex;
	if(win_hwnd_list[index].type != -1){
		for(var i=0; i<win_count;i++){
			index++;
			if(index<win_count){
				if(win_hwnd_list[index].type==-1){
					SetFocusWindow(index);
					g_setfocusIndex = index;
					return index;
				}
			}
			else{
				index=0;
			}
		}
		index++;
		if(index==win_count){
			index =0;
		}
		SetFocusWindow(index);
		g_setfocusIndex = index;
		return index;
	}
	else{
		return index;
	}
	
}

function startplayround()
{
	btn_closeall_click();
	var items = document.getElementsByName("liitem");
	if(items.length==0){
		return;
	}
	else {
		for(var index=0; index<win_count; index++){
			if(g_roundid<items.length){
				var streaminfo = items[g_roundid].getAttribute("data-value");
				playstreamEx(index, JSON.parse(streaminfo));
				g_roundid++;
			}
			else{
				break;
			}
		}
		if(g_roundid >= items.length){
			g_roundid = 0;
		}
	}
	g_roundlistchange = false;
}

function btn_roundstart_click()
{
	startplayround();
	if(g_roundtimer==null){
		g_roundtimer = setInterval(function(){
			var items = document.getElementsByName("liitem");
			if(items.length>win_count || g_roundlistchange){
				startplayround()
			}
		} , 5000);
	}
	document.getElementById("btn_roundend").style.visibility="visible";
	document.getElementById("btn_roundstart").style.visibility="hidden";
}

function btn_roundend()
{
	if(g_roundtimer){
		clearInterval(g_roundtimer);
		btn_closeall_click();
	}
	g_roundtimer = null;
	g_roundid = 0;
	document.getElementById("btn_roundend").style.visibility="hidden";
	document.getElementById("btn_roundstart").style.visibility="visible";
}



function btn_addto_click()
{
	var cam = getStreamPath();
	var strcam = JSON.stringify(cam);

	var items = document.getElementsByName("liitem");
	for (var i = 0; i < items.length; i++) {
		if(items[i].getAttribute("data-value") == strcam){
			return;
		}
	}
	var tag = "<tr><td> <a name='liitem' class='cam-id' data-value='"+strcam+"' href='#'>" + cam.path + "</a></td> <td> <a class='cam-pro'href='#'> 删除</a></td></tr>";
	$('#dev-list').append(tag);
	g_roundlistchange = true; 
}


function btn_stream_play_click()
{
	var stream = getStreamPath();
	var index = GetUsefulIndex();
	playstreamEx(index, stream);

}


function btn_record_play_click()
{
	var stream = getRecordPath();
	var index = GetUsefulIndex();
	playstreamEx(index, stream);
}


function btn_file_play_click()
{
	var stream = GetFilePath();
	var index = GetUsefulIndex();
	playstreamEx(index, stream);
}


function btn_sipstream_play_click()
{
	var stream = GetSipStreamPath();
	var index = GetUsefulIndex();
	playstreamEx(index, stream);
}

function btn_siprecord_play_click()
{
	var stream = GetSipRecordPath();
	var index = GetUsefulIndex();
	playstreamEx(index, stream);
}

function btn_siprecord_download_click()
{
	record_download(GetSipRecordPath(), 0);
}


function playstreamEx(index, stream)
{	
	cleanWindow(index);
	if(IsWindowBusy(index)){
		StopVideo(index,
		function fun1(pos, result, userParam){
			if(result==0){
				playstream(pos, stream);
			}
		}, 0);
	}
	else{
		playstream(index, stream);
	}
}

function playstream(index, stream){
	var gpu = GetHWGpuStatus();
	if(gpu){
		prints("gpustatus = "+JSON.stringify(gpu));
	}
	var mem = GetMemory();
	prints("cpustatus = "+ mem);
	var err = PlayVideo(index, JSON.stringify(stream), 
		function playcb(pos, result, userParam){
			if(result!=0){
				if(result == -21232)
				{
					alert("需要登录！")
					var streams = {};
					if(stream.type==1||stream.type==8)
						streams = getStreamPath2();
					else
						streams = getRecordPath2();
					playstream(index, streams);
					return;
				}
				StopVideo(pos,funnull, 0);
				SetBKImage(pos,1);//无法打开
				SetText(pos, "错误码["+result+"]");
				prints("PlayVideo("+pos+", "+JSON.stringify(stream)+") ="+result);
			}
			else {
				//afterPlayStream(pos, stream);
			}
		},0,
		function firstframecb(pos, result, userParam){
			if(result!=0){
				prints("playstream firstframecb window["+pos+"] error["+result+"]");
				//StopVideo(pos,function fun(pos, result, userParam){
				//		SetBKImage(pos,0);
				//		SetText(pos, "请求流超时");}, 0);
			}
			else{
				//SetOsd(pos);
				setTimeout(function HWdecoderStatus(){
					var res = GetHWdecoderStatus(pos);
					if(res){
						prints("GetHWdecoderStatus("+pos+")="+JSON.stringify(res));
					}
					else{
						prints("GetHWdecoderStatus error");
					}
				}  ,3000);
				

				Getwidthheight(pos);
				GetVideoEncode(pos)
			}
		},0,
		function recordendcb(pos, result, userParam){
			if(result == 0){
				printlog("playstream window "+pos+" recordend");
				//StopVideo(pos,function fun(pos, result, userParam){
				//	SetText(pos, "录像播放结束");}, 0);
			}
		}, 0
	);
	if(err!=0){
		SetBKImage(index, 1);//无法打开
		SetText(index, "错误码["+err+"]");
		prints("PlayVideo("+index+", "+JSON.stringify(stream)+") ="+err);
	}
	afterPlayStream(index, stream)
}

function afterPlayStream(index, stream)
{
	win_hwnd_list[index].path=stream;
	win_hwnd_list[index].type=stream.type;
	if(win_hwnd_list[index].menu != stream.type){
		RemoveMenu(index, win_hwnd_list[index].menu);
		SetMenu(index, stream.type,stream.displayMode,stream.audio);
		win_hwnd_list[index].menu = stream.type;
	}
	SetWindowToolbar(index, stream.type);
	if(index == toolindex){
		ShowWindowToolbar(index,true);
	}

	//MenuEnablePTZ3D(index, 0, 0 ,0,"");

}

function gethwdecoder()
{
	var chkObjs = document.getElementsByName("hwdecoder");
	for(var i=0;i<chkObjs.length;i++){
		if(chkObjs[i].checked){
			return parseInt($(chkObjs[i]).attr('value'));
		}
	}
}

function isPvgplus()
{
	var ispvgplus = false;
	if($('#chk_pvgplus').attr('checked')){
		ispvgplus = true;
	}
	return ispvgplus;
}


function gettype(real){
	var type = 0;
	if(isPvgplus())
	{
		if (real)
		{
			type = 8;
		}
		else{
			type = 9;
		}
	}else {
		if (real)
		{
			type = 1;
		}else{
			type = 2;
		}
	}
	return type;
}

function GetdisplayMode()
{
	var displayMode = 0;
	if($('#chk_displayMode').attr('checked')){
		displayMode = 1;
	}
	return displayMode;
}

function getStreamPath2()
{
	var ticket = {"user":$('#txt_username_login').attr('value'),
		"password":$('#txt_password_login').attr('value')
	};
	ticket = JSON.stringify(ticket);
	var type = gettype(1);
	var stream ={
		"type":type,
		"ticket":ticket,
		"ticketlen":ticket.length,
		"ip": $('#txt_pvgip_login').attr('value'), 
		"port":parseInt($('#txt_port_login').attr('value')),
		"path":$('#txt_avpath').attr('value'),
		"audio":$('#txt_avaudio').attr('value'),
		"displayMode":GetdisplayMode(),
		"hwdecoder":gethwdecoder()
	}
	return stream;
}


function getStreamPath()
{
	var type = gettype(1);
	var stream ={
		"type":type,
		"user":$('#txt_username_login').attr('value'),
		"passwd":$('#txt_password_login').attr('value'),
		"ip": $('#txt_pvgip_login').attr('value'), 
		"port":parseInt($('#txt_port_login').attr('value')),
		"path":$('#txt_avpath').attr('value'),
		"audio":$('#txt_avaudio').attr('value'),
		"displayMode":GetdisplayMode(),
		"hwdecoder":gethwdecoder()
	}
	return stream;
}

function getRecordPath2()
{
	var ticket = {"user":$('#txt_username_login').attr('value'),
		"password":$('#txt_password_login').attr('value')
	};
	ticket = JSON.stringify(ticket);
	var type = gettype(0);
	//var begin=stringParseDate($('#datetime_begin').datebox('getValue') + " " + $('#time_begin').attr('value'));
	//var end=stringParseDate($('#datetime_end').datebox('getValue') + " " + $('#time_end').attr('value'));
	var date=new Date();
	var begin=stringParseDate(date.getFullYear().toString() + "-" + (date.getMonth()+1).toString() + "-"+date.getDate().toString()+" "+(date.getHours()-1).toString() + ":" + date.getMinutes().toString() + ":" + date.getSeconds().toString());
	var end=stringParseDate(date.getFullYear().toString() + "-" + (date.getMonth()+1).toString()+ "-"+date.getDate().toString()+" "+date.getHours() + ":" + date.getMinutes().toString() + ":" + date.getSeconds().toString());

	var vodtype = 0; //parseInt($('#vodtype').attr('value'));
	var stream ={
		"type":type,
		"ticket":ticket,
		"ticketlen":ticket.length,
		"ip": $('#txt_pvgip_login').attr('value'), 
		"port":parseInt($('#txt_port_login').attr('value')),
		"path":$('#txt_avpath').attr('value'),
		"displayMode":GetdisplayMode(),
		"vodType":vodtype,
		"beginTime":begin,
		"endTime":end,
		"hwdecoder":gethwdecoder()
	}
	return stream;
}

function getRecordPath()
{
	var type = gettype(0);
	//var begin=stringParseDate($('#datetime_begin').datebox('getValue') + " " + $('#time_begin').attr('value'));
	//var end=stringParseDate($('#datetime_end').datebox('getValue') + " " + $('#time_end').attr('value'));
	var date=new Date();
	var begin=stringParseDate(date.getFullYear().toString() + "-" + (date.getMonth()+1).toString() + "-"+date.getDate().toString()+" "+(date.getHours()-1).toString() + ":" + date.getMinutes().toString() + ":" + date.getSeconds().toString());
	var end=stringParseDate(date.getFullYear().toString() + "-" + (date.getMonth()+1).toString()+ "-"+date.getDate().toString()+" "+date.getHours() + ":" + date.getMinutes().toString() + ":" + date.getSeconds().toString());
	var vodtype = 0;//parseInt($('#vodtype').attr('value'));
	var stream ={
		"type":type,
		"user":$('#txt_username_login').attr('value'),
		"passwd":$('#txt_password_login').attr('value'),
		"ip": $('#txt_pvgip_login').attr('value'), 
		"port":parseInt($('#txt_port_login').attr('value')),
		"path":$('#txt_avpath').attr('value'),
		"displayMode":GetdisplayMode(),
		"vodType":vodtype,
		"beginTime":begin,
		"endTime":end,
		"hwdecoder":gethwdecoder()
	}
	return stream;
}

function GetFileType()
{
	var chkObjs = document.getElementsByName("fileType");
	for(var i=0;i<chkObjs.length;i++){
		if(chkObjs[i].checked){
			return parseInt($(chkObjs[i]).attr('value'));
		}
	}
}



function GetFilePath()
{
	var FileType = GetFileType();
	var filename = $('#txt_filepath').attr('value');
	if(FileType == 6|| FileType == 7)
	{
		return GetRtspPath(FileType, filename);
	}else if (FileType == 10|| FileType == 11)
	{
		return GetRTMPHLSPath(FileType, filename);
	}
	var stream = {
		"type":FileType,
		"filename":filename,
		"displayMode":GetdisplayMode(),
		"hwdecoder":gethwdecoder(),
		"repeat":0
	}
	return stream;
}

function Getdgplay()
{
	var storageMode = 0;
	if($('#chk_dgplay').attr('checked')){
		storageMode = 1;
	}
	return storageMode;
}

function GetRtspPath(fileType, filename)
{
	var stream = {
		"type":fileType,
		"url":filename,
		"user":"",
		"password":"",
		"tcp":true,
		"autoreconnect":true,
		"streamtype":Getdgplay(),
		"displayMode":GetdisplayMode(),
		"hwdecoder":gethwdecoder()
	}
	return stream;
}

function GetRTMPHLSPath(fileType, filename)
{
	var stream = {
		"type":fileType,
		"url":filename,
		"displayMode":GetdisplayMode(),
		"hwdecoder":gethwdecoder()
	}
	return stream;
}


function GetSipStreamPath()
{
	var stream ={
		"type":4,
		"user":$('#txt_sipusername_login').attr('value'),
		"passwd":$('#txt_sippassword_login').attr('value'),
		"severip": $('#txt_sipip_login').attr('value'), 
		"severid":$('#txt_sipid_login').attr('value'),
		"severport":parseInt($('#txt_sipport_login').attr('value')),
		"deviceID":$('#txt_sipavpath').attr('value'),
		"displayMode":GetdisplayMode(),
		"hwdecoder":gethwdecoder()
	}
	return stream;
}

function GetisDeviceRcd()
{
	return 0;
	var isDeviceRcd = 0;
	if($('#chk_sipisDeviceRcd').attr('checked')){
		isDeviceRcd = 1;
	}
	return isDeviceRcd;
}

function GetSipVodtype()
{
	return 0; 
	var chkObjs = document.getElementsByName("sipVodtype");
	for(var i=0;i<chkObjs.length;i++){
		if(chkObjs[i].checked){
			return parseInt($(chkObjs[i]).attr('value'));
		}
	}
}

function GetSipRecordPath()
{
	var date=new Date();
	var begin=stringParseDate(date.getFullYear().toString() + "-" + (date.getMonth()+1).toString() + "-"+date.getDate().toString()+" "+(date.getHours()-1).toString() + ":" + date.getMinutes().toString() + ":" + date.getSeconds().toString());
	var end=stringParseDate(date.getFullYear().toString() + "-" + (date.getMonth()+1).toString()+ "-"+date.getDate().toString()+" "+date.getHours() + ":" + date.getMinutes().toString() + ":" + date.getSeconds().toString());
	//var begin=stringParseDate($('#sip_datetime_begin').datebox('getValue') + " " + $('#sip_time_begin').attr('value'));
	//var end=stringParseDate($('#sip_datetime_end').datebox('getValue') + " " + $('#sip_time_end').attr('value'));
	var vodtype =  0; //GetSipVodtype();
	var isDeviceRcd = 0;//GetisDeviceRcd();
	var stream ={
		"type":5,
		"user":$('#txt_sipusername_login').attr('value'),
		"passwd":$('#txt_sippassword_login').attr('value'),
		"severip": $('#txt_sipip_login').attr('value'), 
		"severid":$('#txt_sipid_login').attr('value'),
		"severport":parseInt($('#txt_sipport_login').attr('value')),
		"deviceID":$('#txt_sipavpath').attr('value'),
		"vodType":vodtype,
		"beginTime":begin,
		"endTime":end,
		"displayMode":GetdisplayMode(),
		"hwdecoder":gethwdecoder()
	}
	return stream;
}

function getrofsservertype()
{
	var chkObjs = document.getElementsByName("rofsservertype");
	for(var i=0;i<chkObjs.length;i++){
		if(chkObjs[i].checked){
			return $(chkObjs[i]).attr('value');
		}
	}
}

function GetRofsRecordPath()
{
	var begin=stringParseDate($('#rofs_datetime_begin').datebox('getValue') + " " + $('#rofs_time_begin').attr('value'));
	var end=stringParseDate($('#rofs_datetime_end').datebox('getValue') + " " + $('#rofs_time_end').attr('value'));
	var stream ={
		"type":13,
		"user":$('#txt_rofsuser').attr('value'),
		"passwd":$('#txt_rofspassword').attr('value'),
		"ip": $('#txt_rofsip').attr('value'), 
		"path":$('#txt_rofspath').attr('value'),
		"beginTime":begin,
		"endTime":end,
		"displayMode":GetdisplayMode(),
		"hwdecoder":gethwdecoder(),
		"serverinfo":getrofsservertype()
	};
	return stream;
}

function btn_rofsstream_play_click()
{
	var begin=stringParseDate($('#rofs_datetime_begin').datebox('getValue') + " " + $('#rofs_time_begin').attr('value'));
	var end=stringParseDate($('#rofs_datetime_end').datebox('getValue') + " " + $('#rofs_time_end').attr('value'));
	var stream ={
		"type":12,
		"user":$('#txt_rofsuser').attr('value'),
		"passwd":$('#txt_rofspassword').attr('value'),
		"ip": $('#txt_rofsip').attr('value'), 
		"path":$('#txt_rofspath').attr('value'),
		"displayMode":GetdisplayMode(),
		"hwdecoder":gethwdecoder(),
		"serverinfo":getrofsservertype()
	}
	var index = GetUsefulIndex();
	playstreamEx(index, stream);
}

function btn_rofsrecord_play_click()
{
	var stream = GetRofsRecordPath();
	var index = GetUsefulIndex();
	playstreamEx(index, stream);
}

function btn_rofsrecord_download_click()
{
	var stream = GetRofsRecordPath();
	record_download(stream, 0);
}

function btn_rofsrecord_query_click()
{
	var stream = GetRofsRecordPath();
	var id = QueryRecord(JSON.stringify(stream), QueryRecordCallback2,0)
	prints("QueryRecord="+id);
	if(id<0){
		prints("查询录像失败！"+id);
	}
}


function btn_closeall_click()
{
	for(var i=0; i<win_hwnd_list.length; i++){
		StopStream(i);
	}
}

function StopStream(index)
{
	
	if(win_hwnd_list[index].webid>0){
		CloseWebDialog(win_hwnd_list[index].webid);
		win_hwnd_list[index].webid = 0;
	}
	if(win_hwnd_list[index].reverse)
		win_hwnd_list[index].reverse = false;
		

	// if(IsWindowBusy(index))
	{
		StopVideo(index,
			function fun1(pos, result, userParam){
				if(result==0){
					SetBKImage(pos,0);
				}
			}, 0);
	}
	SetText(index, "");
	SetBKImage(index,0);
	cleanWindow(index);
	
	//ShowMenu(index, false);
}



function cleanWindow(index)
{
	win_hwnd_list[index].path={};
	//if(win_hwnd_list[index].type != -1)
	{
		if(win_hwnd_list[index].webid >0){
			CloseWebDialog(win_hwnd_list[index].webid);
			win_hwnd_list[index].webid = 0;
		}
		RemoveMenu(index, win_hwnd_list[index].type);
		ShowWindowToolbar(index, false);
		var treeNode = win_hwnd_list[index].treenode;
		if(treeNode)
		{
			var bfind = false;
			win_hwnd_list[index].treenode = null;
			for(var i=0; i<win_hwnd_list.length; i++){
				if(win_hwnd_list[i].treenode==treeNode){
					bfind = true;
				}
			}
			if(!bfind){
				treeNode.icon = closeimg;
				var treeObj = $.fn.zTree.getZTreeObj("tvwCamera");
				treeObj.updateNode(treeNode);
			}
		}
		win_hwnd_list[index].menu = -1;
		win_hwnd_list[index].type= -1;
		win_hwnd_list[index].seek= -1;
		win_hwnd_list[index].toolbar = -1;
		win_hwnd_list[index].zoom = false;
		win_hwnd_list[index].ptz = false;
		win_hwnd_list[index].ptz3d = false;
		win_hwnd_list[index].path = {};
		win_hwnd_list[index].dur = 0;
		win_hwnd_list[index].seek = -1;
		win_hwnd_list[index].seektimes = 0;
		//win_hwnd_list[index].maxdtime = 6;
		win_hwnd_list[index].bpause = false;
		win_hwnd_list[index].brange = false;
	}
	
}


//////////右键菜单////////////////////

function CreateMenu(index)
{
	var ratio = GetRatioCode(0);
	var param = InitMenu(ratio);
	//prints("begin");
	var err = CreateJsonMenu(index, param);
	//prints("end");
	
	AddMenuCallBackByID(index, 141, MenuSetRatio);
	AddMenuCallBackByID(index, 142, MenuSetRatio);
	AddMenuCallBackByID(index, 143, MenuSetRatio);
	AddMenuCallBackByID(index, 144, MenuSetRatio);
	AddMenuCallBackByID(index, 145, MenuSetRatio);
	return err;

}

function SetMenu(index, streamType,displayMode,audio)
{
	var param = GetVideoMenu(streamType,displayMode,audio,0, GetEnableWatermark());
	var err = InsertJsonMenu(index,14, param, true);
	AddMenuCallBackByID(index, 10, MenuStop);
	AddMenuCallBackByID(index, 11, MenuEnableZoom);
	AddMenuCallBackByID(index, 12, MenuEnablePTZ);
	AddMenuCallBackByID(index, 13, MenuEnablePTZ3D);
	//AddMenuCallBackByID(index, 15, MenuPTZLock);
	AddMenuCallBackByID(index, 20, MenuStopAll);
	AddMenuCallBackByID(index, 16, MenuAddImage);

	AddMenuCallBackByID(index, 17, MenuTalkback);
	AddMenuCallBackByID(index, 18, MenuCatchPic);
	AddMenuCallBackByID(index, 21, MenuWatermark);
	// AddMenuCallBackByID(index, 171, MenuTalkback);
	// AddMenuCallBackByID(index, 172, MenuTalkback);
	// AddMenuCallBackByID(index, 173, MenuTalkback);

	AddMenuCallBackByID(index, 30, MenuRecordRealStream);
	AddMenuCallBackByID(index,40, MenuReverse);
	AddMenuCallBackByID(index, 311, MenuEnableRealtimePlayback);
	AddMenuCallBackByID(index, 312, MenuStartRealtimePlayback)

}


function ShowMenu(index, bshow)
{
	var param = {
			"id"   : 1
		};
	param = JSON.stringify(param);
	ShowJsonMenu(index, param, bshow);
}


function RemoveMenu(index, streamType)
{
	var param = GetVideoMenu(streamType,0,"",0,false);
	//var param = JSON.stringify({"id": 14});
	RemoveJsonMenu(index, param);
}

function GetEnableWatermark()
{
	var enable = false;
	if($('#chk_EnableWatermark').attr('checked')){
		enable = true;
	}
	return enable;
}


function GetEnableRcdTimerShaft()
{
	var enable = false;
	if($('#chk_EnableRcdTimerShaft').attr('checked')){
		enable = true;
	}
	return enable;
}

function MenuEnableRealtimePlayback(index, menuID, nID,bcheck,sstext)
{
	var enable = !bcheck;
	var param = [{
		"id"      : 311,
		"text"    : "实时预录",
		"check"   : enable
	},
	{
		"id"      : 312,
		"text"    : "开启回放",
		"gray"    : !enable
	}];
	var ret = realprerecord(index, enable, 1000*60*5);
	if(ret==0){
		SetJsonMenu(index, JSON.stringify(param));
	}
}
function startrealtimeplayback(type, id, error, info, userParam)
{
	if(type==0 && error==0)
	{
		var  filename = JSON.parse(info);
		if(filename)
		{
			filename = filename["filename"];
		}
		if(filename)
		{
			var index = userParam;
			var stream = win_hwnd_list[index].path;
			var playback = {
				"type":0,
				"filename":filename,
				"repeat":0   //循环播放
			};
			prints("realtimeplayback "+filename);
			g_realtimestreamparam = JSON.stringify(stream);
			g_playbackstreamparam = JSON.stringify(playback);
			setCookie('realtimestreamaram',g_realtimestreamparam);
			setCookie('playbackstreamaram',g_playbackstreamparam);
			getCookie('realtimeplaybackhtml');
			//if(html==null || html=='closed')
			{
				allowEvent = false;
				window.setTimeout(function confirmLeave(){
					allowEvent=true;
					}  ,1000);
			     
				window.open('./temiframe2.html?'+g_pvaocxdownloadparam , 'download','toolbar=no,location=no,menubar=no,status=yes,scrollbars=no,resizable=yes');
				//$.cookie('pvadownloadhtml','opened',{expires:7});
				setCookie('realtimeplaybackhtml','opened');
			}

		}
	}
	else
	{
		alert("获取预录文件失败");
	}
}
function MenuStartRealtimePlayback(index, menuID, nID,bcheck,sstext)
{
	var id = GetRealPreRecordFile(index,1000*60*5, startrealtimeplayback, index);
}
function MenuRecordRealStream(index, menuID, nID,bcheck,sstext)
{
	var text = "开始录制";
	if(sstext == "开始录制"){
		text = "停止录制";
		var filename = "recordrealstream.mbf";
		if(win_hwnd_list[index].path.title)
			filename = win_hwnd_list[index].path.title+".mbf";
		else 
		{
			filename = win_hwnd_list[index].path.path+".mbf";
			filename.replace("/", "_");
		}
		filename = "D:/pvademo/"+filename;
		var param = {
			"filepath":filename
		}
		param = JSON.stringify(param);
			
		var ret = StartRecordRealStream(index,param);
		prints("StartRecordRealStream("+index+","+param+")="+ret);
	}
	else{
		StopRecordRealStream(index);
	}
	var param = {
				"id"      : 30,
				"text"    : text
			};
	SetJsonMenu(index, JSON.stringify(param));
}


function MenuWatermark(index, menuID, nID,bcheck,sstext)
{
	prints(sstext);
	var text = "删除水印";
	if(sstext == "删除水印"){
		text = "增加水印";
		RemoveWatermark(index, -1);
	}
	else{
		var ret = AddWatermark(index);
		//setTimeout(function(){AddWatermark(index)}, 5000);
		prints("AddWatermark = "+ret);
	}
	
	var param = {
				"id"      : 21,
				"text"    : text
			};
	SetJsonMenu(index, JSON.stringify(param));
}

function MenuTalkback(index, menuID, nID,bcheck,sstext)
{
	prints(bcheck+sstext);
	//var mode = nID - 170;
	var mode = 3;
	if(win_hwnd_list[index].audiomode==0){
		var ret = StartTalkback(index, mode);
		if(ret == 0)
		{
			var param = {
				"id"      : 17,
				"text"    : "语音对讲",
				"check"   : true
			};
			prints(GetJsonMenu(index, JSON.stringify(param)));
			SetJsonMenu(index, JSON.stringify(param));
			win_hwnd_list[index].audiomode = mode;
		}
		else
		{
			prints("StartTalkback("+index+")="+ret);
		}

	}
	else
	{
		var ret = StopTalkback(index);
		var param = {
			"id"      : 17,
			"text"    : "语音对讲",
			"check"   : false
		};
		prints(GetJsonMenu(index, JSON.stringify(param)));
		SetJsonMenu(index, JSON.stringify(param));
		win_hwnd_list[index].audiomode = 0;
	}
}

function MenuStopAll(index, menuID, nID,bcheck,sstext)
{
	prints( bcheck+sstext);
	for(var i=0; i<win_hwnd_list.length; i++){
		StopStream(i);
	}
}


function MenuStop(index, menuID, nID,bcheck,sstext)
{
	prints( bcheck+sstext);
	StopStream(index);
}

function MenuSetRatio(index, menuID,nID,bcheck,sstext)
{
	prints( bcheck+sstext);
	var param = GetCheckRatio(nID);
	prints(GetJsonMenu(index, param));
	SetJsonMenu(index, param);
	return SetRatio(index, nID-140);
}

function MenuAddImage(index, menuID,nID,bcheck,sstext)
{
	prints( bcheck+sstext);
	if(!win_hwnd_list[index].imageexist){
		var ret = CreateImage( "{'singlearrowline',{(0.7,0.4),(0.3,0.1),(0.5,0.2)}, '255' }",index);
			ret = CreateImage( "{'doublelineonearrow',{ (0.2,0.6),(0.6,0.2),(0.4,0.3),(0.3,0.1),(0.5,0.2)},'16711680'}",index);
			ret = CreateImage( "{'rectangle',{(0.1,0.1),(0.1,0.8),(0.8,0.1),(0.8,0.8)},'8421376' ,矩形}",index);
			ret = CreateImage( "{'polygon',{(0s.43,0.1),(0.5,0.15),(0.25,0.9),( 0.7,0.3),(0.64,0.57)},'8388608', 多边形}",index);
			ret = CreateImage( "{'onelinedoublearrow',{(0.2,0.2),(0.8,0.8),(0.4,0.6), (0.6,0.4)},'65280', 单线双箭头}",index);
			ret = 0;
		//var ret = CreateImage(index, strinfo);
		if(ret == 0){
			win_hwnd_list[index].imageexist = true;
			var param = {
				"id"      : 16,
				"text"    : "删除图像"
			};
			prints(GetJsonMenu(index, JSON.stringify(param)));
			SetJsonMenu(index, JSON.stringify(param));
		}
	}
	else
	{
		ReleaseAllImage(index);
		var param = {
				"id"      : 16,
				"text"    : "添加图像"
			};
		SetJsonMenu(index, JSON.stringify(param));
		win_hwnd_list[index].imageexist = false;
	}
	
}

function MenuReverse(index, menuID,nID,bcheck,sstext)
{
	if(!win_hwnd_list[index].reverse){
		//反向
		PlayReverse(1,index);
		win_hwnd_list[index].reverse = true;
		var param = {
			"id"      : 40,
			"text"    : "正向播放"
		};
		SetJsonMenu(index, JSON.stringify(param));
		
	}
	else
	{
		//正向
		PlayReverse(0,index);
		win_hwnd_list[index].reverse = false;
		var param = {
				"id"      : 40,
				"text"    : "反向播放"
			};
		SetJsonMenu(index, JSON.stringify(param));
	}
}

function MenuCatchPic(index, menuID,nID,bcheck,sstext)
{
	prints( bcheck+sstext);
	CaptureAndShow(index);
	// var param = JSON.stringify({"id": 101});
	// RemoveJsonMenu(index, param);

}

////////////数字放大//////////////////////

function ToolbarZoom(strinfo)
{
	prints(strinfo);
	var param = JSON.parse(strinfo);
	var index = param.index;
	var nid = param.key;
	var info = GetToolbarItemStatus(index, nid);
	prints(info);
	if(!JSON.parse(info)){
		prints("GetToolbarItemStatus JSON.parse error");
	}
	//RemoveToolbar(index,-1);
	//RemoveToolbar(index,2);
	prints(GetToolbarItemStatus(index, 1));

	var temp = {  "key":23,
	         "show":true};
	ShowAndEnableToolbarItem(index, JSON.stringify(temp));
}

function MenuEnableZoom(index, menuID,nID,bcheck, sstext)
{
	prints( bcheck+sstext);
	var bEnable = !(win_hwnd_list[index].zoom);
	if(bEnable && win_hwnd_list[index].ptz3d){
		EnablePTZ3DPro(index, false);
	}
	EnableZoomPro(index, bEnable);
}

function EnableZoomPro(index, bEnable)
{
	var err = EnableDigitalZoom(index, bEnable);
	if(err == 0){
		SetMenuZoomStatus(index, bEnable);	
	}
}

function SetMenuZoomStatus(index, bEnable)
{
	var param = {
			"id"      : 11,
			"text"    : "数字放大",
			"check"   : bEnable
		};
	param = JSON.stringify(param);
	prints(GetJsonMenu(index, param));
	SetJsonMenu(index, param);
	win_hwnd_list[index].zoom = bEnable;
}

function HandilyCloseDZoom_change()
{
	var bEnable = false;
	if($('#chk_HandilyCloseDZoom').attr('checked')){
		bEnable=true;
	}
	try{
		var ret = SetHandilyCloseDZoom(bEnable);
	}
	catch (e){
		$('#chk_HandilyCloseDZoom').attr('checked', false);
		alert("不支持此功能");
	}
	var bstatus = GetHandilyCloseDZoom();
	if(bstatus!=bEnable){
		$('#chk_HandilyCloseDZoom').attr('checked', bstatus);
	}
}


function EnablePTZDblclk_change()
{
	var bEnable = false;
	if($('#chk_EnablePTZDblclk').attr('checked')){
		bEnable=true;
	}
	var ret = SetEnablePTZDblclk(bEnable);
	var bstatus = GetEnablePTZDblclk();
	if(bstatus!=bEnable){
		$('#chk_EnablePTZDblclk').attr('checked', bstatus);
	}
}


function EnablePIP_change()
{
	var bEnable = false;
	if($('#chk_EnablePIP').attr('checked')){
		bEnable=true;
	}
	var ret = EnablePIP(bEnable);
}

function useptzand3dptz_change()
{
	var bEnable = false;
	if($('#chk_useptzand3dptz').attr('checked')){
		bEnable=true;
	}
	var ret = EnableUsePtzand3Dptz(bEnable);
}


/////////////PTZ//////////////////////


function ptzEnable_change()
{
	var bEnable = false;
	if($('#chk_ptzEnable').attr('checked')){
		bEnable=true;
	}
	var ret = EnablePTZ(bEnable);
}

function btn_ptz_mousedown(cmd,bval)
{
	//var speed=$('#cbo_ptz_speed').combobox('getValue');
	var speed=parseInt($('#cbo_ptz_speed').attr('value'));

	if(speed=="")
		speed=5;
	speed=parseInt(speed);
	if(bval)
		speed=0-speed;
	
	if(cmd==9)
		speed=0;

	var index = GetFocesIndex();
	PtzControl(index,cmd,speed);
	
}
function btn_ptz_mouseup(cmd)
{
	var index = GetFocesIndex();
	PtzControl(index,cmd,0);
	
}

function btn_ptz_ptzlock_click()
{
	var time = parseInt($('#ptzlocktime').attr('value'));
	var index = GetFocesIndex();
	var err = PtzLock(index, time);
}




function MenuEnablePTZ(index, menuID,nID,bcheck,sstext)
{
	prints( bcheck+sstext);
	var bEnable = !(win_hwnd_list[index].ptz);
	var err = EnableWindowPTZ(index, bEnable);
	if(err == 0){
		var param = {
			"id"      : 12,
			"text"    : "窗口云台",
			"check"   : bEnable
		};
		prints(GetJsonMenu(index, JSON.stringify(param)));
		param = JSON.stringify(param);
		SetJsonMenu(index, param);
		win_hwnd_list[index].ptz = bEnable;	
	}
}
function MenuEnablePTZ3D(index, menuID,nID,bcheck,sstext)
{
	prints( bcheck+sstext);
	var bEnable = !(win_hwnd_list[index].ptz3d);
	if(bEnable && win_hwnd_list[index].zoom){
		EnableZoomPro(index, false);
	}
	EnablePTZ3DPro(index, bEnable);
}

function EnablePTZ3DPro(index, bEnable)
{
	var err = EnableWindowPTZ3D(index, bEnable);
	if(err == 0){
		var param = {
			"id"      : 13,
			"text"    : "3D云台",
			"check"   : bEnable
		};
		prints(GetJsonMenu(index, JSON.stringify(param)));
		param = JSON.stringify(param);
		SetJsonMenu(index, param);
		win_hwnd_list[index].ptz3d = bEnable;	
	}
}

// function MenuPTZLock(index, menuID,nID)
// {
// 	var err = PtzLock(index, 86400);
// 	if(err == 0){
// 		var param = {
// 			"id"      : 15,
// 			"text"    : "云台锁定",
// 			"check"   : bEnable
// 		};
// 		param = JSON.stringify(param);
// 		SetJsonMenu(index, param);
// 	}
// }

/////////////工具条////////////////

function CreateWindowToolbar(index)
{
	
	var bottomTool = InitToolbarBottom();
	var err = CreateToolbar(index, JSON.stringify(bottomTool));
	if(err == 0){
		win_hwnd_list[index].toolbarBottom = bottomTool.items;
	}
	var topTool = InitToolbarTop();
	err = CreateToolbar(index, JSON.stringify(topTool) );
	if(err == 0){
		win_hwnd_list[index].toolbarTop = topTool.items;
	}
	SetToolbarCallBack("ToolbarStop", ToolbarStop);
	SetToolbarCallBack("ToolbarSoundTrue", ToolbarSoundTrue);
	SetToolbarCallBack("ToolbarSoundFalse", ToolbarSoundFalse);
	SetToolbarCallBack("ToolbarCapture", ToolbarCapture);
	SetToolbarCallBack("ToolbarContinuousCapture", ToolbarContinuousCapture);
	SetToolbarCallBack("ToolbarPTZ", ToolbarPTZ);
	

	SetToolbarCallBack("ToolbarPlayStream", ToolbarPlayStream);
	SetToolbarCallBack("ToolbarPlayRecord", ToolbarPlayRecord);
	SetToolbarCallBack("ToolbarPlaySlow", ToolbarPlaySlow);
	SetToolbarCallBack("ToolbarPlayFast", ToolbarPlayFast);
	SetToolbarCallBack("ToolbarPauseTrue", ToolbarPauseTrue);
	SetToolbarCallBack("ToolbarPauseFalse", ToolbarPauseFalse);
	SetToolbarCallBack("ToolbarPlayStep", ToolbarPlayStep);

	SetToolbarCallBack("ToolbarPosChange", ToolbarPosChange);
	SetToolbarCallBack("ToolbarMouseOnChannal", ToolbarMouseOnChannal);
	SetToolbarCallBack("ToolbarRangeChange", ToolbarRangeChange);
	SetToolbarCallBack("ToolbarPlayRange", ToolbarPlayRange);
	SetToolbarCallBack("ToolbarPlayRangeCancel", ToolbarPlayRangeCancel);

	SetToolbarCallBack("ToolbarMenu", ToolbarMenu);
	SetToolbarCallBack("ToolbarRemoveDraw", ToolbarRemoveDraw);
	
	return err;
}

function ToolbarMenu(szinfo)
{
	prints(szinfo);
	var param = JSON.parse(szinfo);
	var index = param.index;
	var menuid = param.menuid;
	var menucheck = param.check;
	var bstopdraw = true;
	for(var id = 1; id<=5; id++){
		var bcheck = false;
		if(id == menuid){
			if(!menucheck){
				bcheck = true;
				startdrawing(index, menuid-1);
				bstopdraw = false;
			}
		}
		var pin = {
			"menuid": id,
			"check":bcheck
		}
		SetToolbarMenuStatus(index,JSON.stringify(pin));
	}
	if(bstopdraw)
	{
		CloseRealDraw(index);
	}
}

function startdrawing(index, type)
{
	var param = {
		"type":type,
		"linewidth":2,
		"linecolor":255<<(type*8),
		"linetype":1,
		"distance":0.02
	}
	if(type==3) {
		param.linecolor = 0x00ff00ff;
	} else if(type ==4){
		param.linecolor = 0x00ffff00;
	}
	param = JSON.stringify(param);
	OpenRealDraw(index, param)
}

function ToolbarRemoveDraw(strinfo)
{
	var param = JSON.parse(strinfo);
	var index = param.index;
	if (bselectrealdrawObjectID)
	{
		RemoveRealDrawObject(index,selectrealdrawObjectID);
		ResetToolbarStatus(index, param.key);
	}
}


function ShowWindowToolbar(index, bshow)
{
	if(win_hwnd_list==null)
		return;
	if(bshow && win_hwnd_list[index].type ==-1){
		return;
	}
	if(win_hwnd_list[index].type !=-1){
		ShowToolbar(index, bshow);
		win_hwnd_list[index].showToolbar = bshow;
	}

	if(bshow){
		if(!win_hwnd_list[index].timerToolbar){
			var timer = setInterval(function(){UpdateToolbar(index)} , 500);
			win_hwnd_list[index].timerToolbar = timer;
		}
	}
	else{
		if(win_hwnd_list[index].timerToolbar){
			clearInterval(win_hwnd_list[index].timerToolbar);
			win_hwnd_list[index].timerToolbar = null;
		}
	}

}

function AdjustToolbarItem(index)
{
	if(!win_hwnd_list)
		return;
	if(win_hwnd_list[index].type ==-1 && !win_hwnd_list[index].showToolbar){
		return;
	}
	GetVideToolbarTopObjs(win_hwnd_list[index].toolbarTop, win_hwnd_list[index].type,  isSoundEnable(index),  win_hwnd_list[index].path.displayMode, win_hwnd_list[index].path.istrack);
	var Toolobj = win_hwnd_list[index].toolbarTop;
	if(Toolobj)
	{
		for(var i=0; i<Toolobj.length; i++){
			var info=JSON.stringify(Toolobj[i]);
			ShowAndEnableToolbarItem(index, info);
		}	
	}
	

	GetVideToolbarBottomObjs(win_hwnd_list[index].toolbarBottom, win_hwnd_list[index].type,  GetWindowRectWidth(index), win_hwnd_list[index].brange, win_hwnd_list[index].bpause);
	Toolobj = win_hwnd_list[index].toolbarBottom;
	if(Toolobj)
	{
		for(var i=0; i<Toolobj.length; i++){
			var info=JSON.stringify(Toolobj[i]);
			ShowAndEnableToolbarItem(index, info);
		}
	}
}


function SetWindowToolbar(index, streamType)
{
	var text25 = GetVideotype(streamType);
	SetToolbarStaticContent(index, 25, text25);

	AdjustToolbarItem(index);
	for(var id = 1; id<=3; id++){
		var pin = {
			"menuid": id,
			"check":false
		}
		SetToolbarMenuStatus(index,JSON.stringify(pin));
	}

	if(isStream(streamType)){
		return;
	} 
	if(isRecord(streamType)){
		var dur = 0;
		if (streamType == 13)
		{
		    dur = Math.floor(GetDuration(index));
		}else{
		var begin = win_hwnd_list[index].path.beginTime;
		var end   = win_hwnd_list[index].path.endTime;
		    dur = GetDurationRecord(end, begin);
		}
		if(dur>=0){
			win_hwnd_list[index].dur = dur;
			ResetToolbarPlayStatus(index, dur);
		}

	}
	else{
		var dur = Math.floor(GetDuration(index));
		if(dur>=0){
			win_hwnd_list[index].dur = dur;
			ResetToolbarPlayStatus(index, dur);
		}
		prints("GetDuration("+index+") = "+dur+"S");
	}
	SetToolbarProgressPos(index, 19, 0);
	setToolbarFrameFlag(index, 19, 0, 0, false);
	SetToolbarStaticContent(index, 102, "00:00:00");
	UpdatePlaySpeed(index);
	UpdateToolbar(index);
}

function ResetToolbarPlayStatus(index, dur)
{
	var text = GetDueString(dur);
	SetToolbarStaticContent(index, 101, text);
	
	SetToolbarProgressRange(index, 19, dur);
}


function UpdateToolbar(index)
{
	// var ret = GetAllZoomStatus();
	// prints("GetAllZoomStatus() = " +ret);

	if(win_hwnd_list[index].type == -1){
		return;
	}
	var speed = GetTransferSpeed(index);
	var fps = GetFrameRate(index);
	SetToolbarStaticContent(index, 26, speed+" " +fps);

	if(win_hwnd_list[index].dur>0){
		var time = Math.floor(GetPlayTime(index));
		if(time>=0 && time<=win_hwnd_list[index].dur){
			if((win_hwnd_list[index].seek==-1)){
				SetToolbarProgressPos(index, 19, time);
				var strtime = GetDueString(time)
				SetToolbarStaticContent(index, 102, strtime);
			}
			else{
				var dtime = time - win_hwnd_list[index].seek;
				//var maxdtime = win_hwnd_list[index].maxdtime;
				if(dtime>-1 && dtime<=6){
					win_hwnd_list[index].seek = -1;
					SetToolbarProgressPos(index, 19, time);
					var strtime = GetDueString(time)
					SetToolbarStaticContent(index, 102, strtime);
					prints("seek dtime OK "+dtime);
				}
				else{
					win_hwnd_list[index].seektimes += 1;
					prints("seek dtime error"+dtime+","+win_hwnd_list[index].seektimes);
					if(win_hwnd_list[index].seektimes>6){
						win_hwnd_list[index].seek = -1;	
					}
				}
			}
		}	
	}
	else 
	{
		var streamType = win_hwnd_list[index].type;
		if(streamType == 0 || streamType == 3 || streamType == 7 || streamType == 13){
			var dur = Math.floor(GetDuration(index));
			if(dur>0){
				win_hwnd_list[index].dur = dur;
				ResetToolbarPlayStatus(index, dur);
			}
			prints("GetDuration("+index+")="+ dur);
		}	
	}
}

function ToolbarStop(strinfo)
{
	var param = JSON.parse(strinfo);
	ResetToolbarStatus(param.index, 21);
	StopStream(param.index);
}



function ToolbarPlayStream(strinfo)
{
	var param = JSON.parse(strinfo);
	var index = param.index;
	if(win_hwnd_list[index].type == 2 || win_hwnd_list[index].type == 9)
	{
		var stream = win_hwnd_list[index].path;
		stream.type = win_hwnd_list[index].type-1;
		win_hwnd_list[index].seek= -1;
		win_hwnd_list[index].zoom = false;
		win_hwnd_list[index].ptz = false;
		win_hwnd_list[index].ptz3d = false;
		win_hwnd_list[index].dur = 0;
		win_hwnd_list[index].seek = -1;
		playstreamEx(index, stream);
	}
	else if(win_hwnd_list[index].type == 5)
	{
		var stream = win_hwnd_list[index].path;
		stream.type = 4;
		win_hwnd_list[index].seek= -1;
		win_hwnd_list[index].zoom = false;
		win_hwnd_list[index].ptz = false;
		win_hwnd_list[index].ptz3d = false;
		win_hwnd_list[index].dur = 0;
		win_hwnd_list[index].seek = -1;
		playstreamEx(index, stream);
	}
}


function ToolbarPlayRecord(strinfo)
{
	var param = JSON.parse(strinfo);
	var index = param.index;
	if(win_hwnd_list[index].type == 1 || win_hwnd_list[index].type == 8)
	{
		var stream = win_hwnd_list[index].path;
		stream.type = win_hwnd_list[index].type+1;
		//var begin=stringParseDate($('#datetime_begin').datebox('getValue') + " " + $('#time_begin').attr('value'));
		//var end=stringParseDate($('#datetime_end').datebox('getValue') + " " + $('#time_end').attr('value'));
		var date=new Date();
		var begin=stringParseDate(date.getFullYear().toString() + "-" + (date.getMonth()+1).toString() + "-"+date.getDate().toString()+" "+(date.getHours()-1).toString() + ":" + date.getMinutes().toString() + ":" + date.getSeconds().toString());
		var end=stringParseDate(date.getFullYear().toString() + "-" + (date.getMonth()+1).toString()+ "-"+date.getDate().toString()+" "+date.getHours() + ":" + date.getMinutes().toString() + ":" + date.getSeconds().toString());

		var vodtype = 0;//$('#vodtype').attr('value');
		stream.vodType = parseInt(vodtype);
		stream.beginTime = begin;
		stream.endTime = end;
		win_hwnd_list[index].seek= -1;
		win_hwnd_list[index].zoom = false;
		win_hwnd_list[index].ptz = false;
		win_hwnd_list[index].ptz3d = false;
		win_hwnd_list[index].dur = 0;
		win_hwnd_list[index].seek = -1;
		playstreamEx(index, stream);
	}
	else if(win_hwnd_list[index].type == 4){
		var stream = win_hwnd_list[index].path;
		stream.type = 5;
		//var begin=stringParseDate($('#sip_datetime_begin').datebox('getValue') + " " + $('#sip_time_begin').attr('value'));
		//var end=stringParseDate($('#sip_datetime_end').datebox('getValue') + " " + $('#sip_time_end').attr('value'));
		var date=new Date();
		var begin=stringParseDate(date.getFullYear().toString() + "-" + (date.getMonth()+1).toString() + "-"+date.getDate().toString()+" "+(date.getHours()-1).toString() + ":" + date.getMinutes().toString() + ":" + date.getSeconds().toString());
		var end=stringParseDate(date.getFullYear().toString() + "-" + (date.getMonth()+1).toString()+ "-"+date.getDate().toString()+" "+date.getHours() + ":" + date.getMinutes().toString() + ":" + date.getSeconds().toString());
		var vodtype = 0;//GetSipVodtype();
		var isDeviceRcd = 0;//GetisDeviceRcd();
		stream.beginTime = begin;
		stream.endTime = end;
		stream.vodType = vodtype;
		stream.isDeviceRcd = isDeviceRcd;
		win_hwnd_list[index].seek= -1;
		win_hwnd_list[index].zoom = false;
		win_hwnd_list[index].ptz = false;
		win_hwnd_list[index].ptz3d = false;
		win_hwnd_list[index].dur = 0;
		win_hwnd_list[index].seek = -1;
		playstreamEx(index, stream);
	}
}

function ToolbarPlaySlow(strinfo)
{
	var param = JSON.parse(strinfo);
	var index = param.index;
	if(win_hwnd_list[index].bpause){
		ToolbarPauseFalse(strinfo);
	}
	PlaySlow(index);
	ResetToolbarStatus(index, 14);
	UpdatePlaySpeed(index);

}

function ToolbarPlayFast(strinfo)
{
	var param = JSON.parse(strinfo);
	var index = param.index;
	if(win_hwnd_list[index].bpause){
		ToolbarPauseFalse(strinfo);
	}
	PlayFast(index);
	ResetToolbarStatus(index, 17);
	UpdatePlaySpeed(index);
}

function ToolbarPauseTrue(strinfo)
{
	var param = JSON.parse(strinfo);
	var index = param.index;
	Pause(index, true);
	ResetToolbarStatus(index, 15);
	ToolbarPlayPause(index, true);
}

function ToolbarPauseFalse(strinfo)
{
	var param = JSON.parse(strinfo);
	var index = param.index;
	Pause(index, false);
	ResetToolbarStatus(index, 151);
	ToolbarPlayPause(index, false);
	UpdatePlaySpeed(index);
}
function ToolbarPlayStep(strinfo)
{
	var param = JSON.parse(strinfo);
	var index = param.index;
	PlayStep(index);
	ResetToolbarStatus(index, 16);
	ToolbarPlayPause(index, true);
}

function ToolbarPlayPause(index, bpause)
{
	win_hwnd_list[index].bpause = bpause;
	var toolbarinfo = win_hwnd_list[index].toolbarBottom;
	replaceToolbarItem(index, toolbarinfo, 151, 15, bpause);
}


function UpdatePlaySpeed(index)
{
	var speed = GetPlaySpeed(index);
	if(speed != "ERROR"){
		//var maxdtime = GetMaxdtime(speed);
		//win_hwnd_list[index].maxdtime = maxdtime;
		speed = "x"+speed;
		SetToolbarStaticContent(index, 18, speed);
	}
	else{
		speed = "x1";
		SetToolbarStaticContent(index, 18, speed);
		prints("GetPlaySpeed("+index+") = error");
	}
}


function ToolbarPosChange(strinfo)
{
	prints(strinfo);
	var param = JSON.parse(strinfo);
	var index = param.index;
	var err = PlaySeek(index, param.pos);
	prints("playseek("+index+", "+param.pos+")="+err);
	if(err==0){
		win_hwnd_list[index].seek = param.pos;
		win_hwnd_list[index].seektimes = 0;
	}
	else{
		prints("playseek("+index+", "+param.pos+")="+err);
	}
	/*
	if(win_hwnd_list[index].brange){
		setToolbarFrameFlag(index, 19, 0, 0, false);
		PlayRange(index, 0, 0, false, function(){}, 0);
		win_hwnd_list[index].brange = false;
	}
	*/
	
}



function ToolbarMouseOnChannal(strinfo)
{
	var param = JSON.parse(strinfo);
	var index = param.index;
	var tip = GetDueString(param.pos);
	SetToolbarProgressToolTip(index, 19, tip);
}

function replaceToolbarItem(index, toolbarinfo, key1, key2, enablekey1)
{
	var indexkey1=-1;
	var indexkey2=-1;
	for(var i=0; i<toolbarinfo.length;i++){
		if(toolbarinfo[i].key == key1){	
			indexkey1 = i;
		}
		else if(toolbarinfo[i].key == key2){
			indexkey2 = i;
		}
		if(indexkey1!=-1&&indexkey2!=-1){
			break;
		}
	}

	if(indexkey1===-1&&indexkey2===-1){
		return;
	}


	if(toolbarinfo[indexkey1].show || toolbarinfo[indexkey2].show)
	{

		if(toolbarinfo[indexkey2].show){
			toolbarinfo[indexkey1].x = toolbarinfo[indexkey2].x;
			toolbarinfo[indexkey1].y = toolbarinfo[indexkey2].y;
			toolbarinfo[indexkey1].width = toolbarinfo[indexkey2].width;
			toolbarinfo[indexkey1].height = toolbarinfo[indexkey2].height;
		}
		else{
			toolbarinfo[indexkey2].x = toolbarinfo[indexkey1].x;
			toolbarinfo[indexkey2].y = toolbarinfo[indexkey1].y;
			toolbarinfo[indexkey2].width = toolbarinfo[indexkey1].width;
			toolbarinfo[indexkey2].height = toolbarinfo[indexkey1].height;
		}
		

		toolbarinfo[indexkey1].show=enablekey1;
		toolbarinfo[indexkey2].show=!enablekey1;

		//MoveToolBarItem(index, JSON.stringify(toolbarinfo[indexkey1]));
		//MoveToolBarItem(index, JSON.stringify(toolbarinfo[indexkey2]));

		ShowAndEnableToolbarItem(index, JSON.stringify(toolbarinfo[indexkey1]));
		ShowAndEnableToolbarItem(index, JSON.stringify(toolbarinfo[indexkey2]));
	}
}

function ToolbarSound(index, benable)
{
	var toolbarinfo = win_hwnd_list[index].toolbarTop;
	replaceToolbarItem(index, toolbarinfo, 27, 271, !benable);
}

function ToolbarSoundTrue(strinfo)
{
	var param = JSON.parse(strinfo);
	var index = param.index;
	SoundEnable(index, true);
	ResetToolbarStatus(index, 27);
	ToolbarSound(index, isSoundEnable(index));
}
function ToolbarSoundFalse(strinfo)
{
	var param = JSON.parse(strinfo);
	var index = param.index;
	SoundEnable(index, false);
	ResetToolbarStatus(index, 271);
	ToolbarSound(index, isSoundEnable(index));
}


function ToolbarCapture(strinfo)
{
	var param = JSON.parse(strinfo);
	var index = param.index;
	CaptureAndShow(index);
}

function CaptureAndShow(index)
{
	var pic = catchScaleDownPicture(index,3, 300, 0);
	var pic2 = GetRawPicture(index, 3);
	ResetToolbarStatus(index, 23);

	// $('#win_picture').window({
	// 		modal: true,
	// 		shadow: false,
	// 		closed: false
	// 	});	
	//$('#win_picture').window('open');
	//$('#win_picture').click();
	var tag = '<div id="pic_div"> <img src="'+"data:image/jpeg;base64,"+pic+'"> </img></div>';
	//var tag = '<div id="pic_div"> <img src="C:/Users/dell/Desktop/123.jpg"> </img></div>';
	if($("#pic_div")[0]){
		$("#pic_div").remove();
	}	
	$('#win_picture').append(tag);
	$('#div_menu').accordion('select','抓图图片');  
}

function ToolbarContinuousCapture(strinfo)
{
	var param = JSON.parse(strinfo);
	var index = param.index;
	var nid = param.key;
	prints(GetToolbarItemStatus(index, nid));
	var ret = ContinuousCatchScaleDownPictures(index,3, 0, 0,1, 10, 
		function(id,  result,  brPicture, brRawPicture, userParam){
			prints("ContinuousCapture("+id+", "+result+", piclen("+brPicture.length+"), rawpiclen("+brRawPicture.length+")");
		}, 0);
	ResetToolbarStatus(index, 28);
}

function ToolbarPlayRange(strinfo)
{
	prints(strinfo);
	var param = JSON.parse(strinfo);
	var index = param.index;
	var dur = win_hwnd_list[index].dur;
	var start = Math.floor(dur/4);
	var end = dur - start - 1;
	setToolbarFrameFlag(index, 19, start, end, true);
	win_hwnd_list[index].brange = true;
	PlayRange(index, start, end,false, function fun(pos,result,userParam){
			prints("playRange end("+pos+", "+start+" ,"+end+", false)");
		}, 0)
	var toolbarObjs = getRangeToolbarObjs(win_hwnd_list[index].type, true);
	for(var i=0; i<toolbarObjs.length; i++){
		var info=JSON.stringify(toolbarObjs[i]);
		ShowAndEnableToolbarItem(index, info);
	}

}
function ToolbarPlayRangeCancel(strinfo)
{
	var param = JSON.parse(strinfo);
	var index = param.index;
	setToolbarFrameFlag(index, 19, 0, 0, false);
	win_hwnd_list[index].brange = false;
	PlayRange(index, 0, 0, false, function(){}, 0);
	var toolbarObjs = getRangeToolbarObjs(win_hwnd_list[index].type, false);
	for(var i=0; i<toolbarObjs.length; i++){
		var info=JSON.stringify(toolbarObjs[i]);
		ShowAndEnableToolbarItem(index, info);
	}
}

function ToolbarRangeChange(strinfo)
{
	var param = JSON.parse(strinfo);
	var index = param.index;
	var nid = param.key;
	prints(GetToolbarItemStatus(index, nid));
	var err = PlayRange(index, param.startPos, param.endPos, true, function(){}, 0)
}



function ToolbarPTZ(strinfo)
{
	var param = JSON.parse(strinfo);
	var index = param.index;
	ResetToolbarStatus(index, 29);

	var webid = win_hwnd_list[index].webid;
	if(webid>0){
		var info={"show":""};
		var ret = GetWebDialog(webid,JSON.stringify(info));
		info = {"show":true}
		ret = SetWebDialog(webid, JSON.stringify(info));
	}
	else{
		var webinfo = GetPtzWebinfo();
		webid = OpenWebDialog(webinfo);
		win_hwnd_list[index].webid = webid;

		// function webevent()
		// {
		// 	prints("WebDialogEvent("+index+")");
		// }
		// detachEventEx(pixwin, 'WebDialogEvent',funweb);
		// funweb = webevent;
		// attachEventEx(pixwin, 'WebDialogEvent',funweb);
		

		setTimeout(function(){
			//var res = ExeScript(webid, "importData", "ExeScript");
			//prints("ExeScript = "+res)
			//CloseWebDialog(webid);
		},5000);
	}
}


function btn_record_query_click()
{
	var stream = getRecordPath();
	var id = QueryRecord(JSON.stringify(stream), QueryRecordCallback2,0)
	prints("QueryRecord="+id);
	if(id<0){
		prints("查询录像失败！"+id);
	}
}

function QueryRecordCallback2(id, info, userdata)
{
	var obj = JSON.parse(info);
	if(!obj || !obj["items"]){
		prints("查询录像失败！");
		return;
	}
	prints("QueryRecordCallback2("+id+","+info+","+userdata+")");
}


function btn_record_download_click()
{
	record_download(getRecordPath(), 0);
}

function GetstorageMode()
{
	var storageMode = 0;
	if($('#chk_storageMode').attr('checked')){
		storageMode = 1;
	}
	return storageMode;
}

function getdownloadPfsPath()
{
	var param = {
		"src": 
		{
			"ip": $('#txt_pfsip_login').attr('value'), 
			"port":parseInt($('#txt_pfsport_login').attr('value')),
			"username":"admin",
			"password":"admin",
			"path":$('#txt_pfspath_login').attr('value'),
			"storagemode":GetstorageMode()
		},
		"filename":"" //下载到本地的存储文件名
	}
	return param;
}

function btn_pfs_download_click()
{
	record_download(getdownloadPfsPath(), 1);
}


function GetUploadFileType()
{
	var chkObjs = document.getElementsByName("uploadfileType");
	for(var i=0;i<chkObjs.length;i++){
		if(chkObjs[i].checked){
			return parseInt($(chkObjs[i]).attr('value'));
		}
	}
}

function getuploadPfsPath()
{
	var param = {
		"filetype":GetUploadFileType(), //1 图片 2 视频 3 其他格式
		"src": $('#txt_filepath2').attr('value'),
		"dest":{
			"ip": $('#txt_pfsip_login').attr('value'), 
			"port":parseInt($('#txt_pfsport_login').attr('value')),
			"username":"admin",
			"password":"admin",
			"path":$('#txt_pfspath_login').attr('value'),
			"storagemode":GetstorageMode()
		}
	};
	return param;
}

function btn_pfs_upload_click()
{
	record_download(getuploadPfsPath(), 2);
}


function btn_pfs_delete_click()
{
	var param = {
			"ip": $('#txt_pfsip_login').attr('value'), 
			"port":parseInt($('#txt_pfsport_login').attr('value')),
			"username":"admin",
			"password":"admin",
			"path":$('#txt_pfspath_login').attr('value')
		};
	var ret= DeletePFSFile(JSON.stringify(param));
	prints("DeletePFSFile="+ret);
}

function getdownloadhttpPath()
{
	var param = {
		"src": $('#txt_filepath3').attr('value'), 
		"filename":"" //下载到本地的存储文件名
	}
	return param;
}
function btn_http_download_click()
{
	record_download(getdownloadhttpPath(), 3);
}


//type 0:pvg pvg+ sip rofs录像下载 1:PFS下载 2:PFS上传 3:HTTP下载
function record_download(path, type) 
{		
	
	if($('#chk_fastdownload').attr('checked')){
		path.downloadtype = 0;
	}
	else{
		path.downloadtype = 1;	
	}				
	g_pvaocxdownloadparam = JSON.stringify(path);
	g_pvaocxdownloadtype = type;
	//$.cookie('pvadownloadparam',g_pvaocxdownloadparam);
	//var html =$.cookie('pvadownloadhtml');
	setCookie('pvadownloadparam',g_pvaocxdownloadparam);
	setCookie('pvadownloadtype',g_pvaocxdownloadtype);
	getCookie('pvadownloadhtml');
	//if(html==null || html=='closed')
	{
		allowEvent = false;
		window.setTimeout(function confirmLeave(){
			allowEvent=true;
			}  ,1000);
	     
		window.open('./temiframe.html?'+g_pvaocxdownloadparam , 'download', 'top=300,left=350,width=700,height=400,toolbar=no,location=no,menubar=no,status=yes,scrollbars=no,resizable=yes,');
		//$.cookie('pvadownloadhtml','opened',{expires:7});
		setCookie('pvadownloadhtml','opened');
	}

}
///////////////////////////////
function menutree_ServerRecord( isstart)
{
	var stream = {};
	if(g_loginfo.type == 4)
	{
		stream = {
			"type":g_loginfo.type,
			"user":g_loginfo.user,
			"passwd":g_loginfo.passwd,
			"severip": g_loginfo.severip, 
			"severid":g_loginfo.severid,
			"severport":g_loginfo.severport,
			"deviceID":tree_target.data
		};
	}
	else
	{
		stream = {
			"type":g_loginfo.type,
			"user":g_loginfo.user,
			"passwd":g_loginfo.passwd,
			"ip":g_loginfo.ip, 
			"port":g_loginfo.port,
			"path":tree_target.data,
			"devid":tree_target.devid,
			"chnlid":tree_target.chnlid
		};
	}

	if(isstart){
		if(StartServerRecord(JSON.stringify(stream))== 0)
		{
			tree_target.isrecording = true;
		}
		else
		{
			alert("StartServerRecord error");
		}
	}
	else
	{
		StopServerRecord(JSON.stringify(stream));
		tree_target.isrecording = false;
	}
		
}


////////////查询录像///////////////

function menutree_queryrecord(isDeviceVod)
{
	
	// var top = $("body").height()-$('#win_queryrecord').height()-50;
	// $('#win_queryrecord').window({
	// 	left:"0px", top:top+"px"
	// });
	// $('#win_queryrecord').window('open');
	//$('#win_pixwin').hide();

	tree_target_record = tree_target;
	$('#query_name').attr('disabled',"true"); 
	$('#query_name').attr('value',tree_target_record.name);
	$('#query_name').attr('disabled',"false"); 

	var date=new Date();
	var begin=date.getFullYear().toString() + "-" + (date.getMonth()+1).toString() + "-"+date.getDate().toString();
	var end=date.getFullYear().toString() + "-" + (date.getMonth()+1).toString()+ "-"+date.getDate().toString();
	$('#query_datetime_begin').datebox('setValue',begin);
	$('#query_datetime_end').datebox('setValue',end);
	begin=(date.getHours()-1).toString() + ":" + date.getMinutes().toString() + ":" + date.getSeconds().toString()+".000";
	end=date.getHours() + ":" + date.getMinutes().toString() + ":" + date.getSeconds().toString()+".000";
	$('#query_time_begin').attr('value',begin);
	$('#query_time_end').attr('value',end);

	if(isDeviceVod){
		$('#query_vodtype').attr('value',1);
	}
	else
	{
		$('#query_vodtype').attr('value',0);
	}

	btn_query_ok_click()
}
function getqueryrecordpath()
{
	var begin=stringParseDate($('#query_datetime_begin').datebox('getValue') + " " + $('#query_time_begin').attr('value'));
	var end=stringParseDate($('#query_datetime_end').datebox('getValue') + " " + $('#query_time_end').attr('value'));
	var vodtype = parseInt($('#query_vodtype').attr('value'));
	
	if(g_loginfo.type == 4)
	{
		var record = {
			"type":g_loginfo.type+1,
			"user":g_loginfo.user,
			"passwd":g_loginfo.passwd,
			"severip": g_loginfo.severip, 
			"severid":g_loginfo.severid,
			"severport":g_loginfo.severport,
			"deviceID":tree_target_record.data,
			"beginTime":begin,
			"endTime":end,
			"vodType":vodtype
		}
		return record;
	}
	else
	{
		var record = {
			"type":g_loginfo.type+1,
			"user":g_loginfo.user,
			"passwd":g_loginfo.passwd,
			"ip":g_loginfo.ip, 
			"port":g_loginfo.port,
			"title":tree_target_record.name,
			"path":tree_target_record.data,
			"devid":tree_target_record.devid,
			"chnlid":tree_target_record.chnlid,
			"beginTime":begin,
			"endTime":end,
			"vodType":vodtype
		}
		return record;
	}
}
	
	
function btn_query_ok_click()
{
	if(!tree_target_record)
		return;
	$('#record-list').empty();
	var record = getqueryrecordpath();
	tree_target_record["vodtype"] = record.vodType;
	//$('#win_queryrecord').window('close');
	//$('#win_pixwin').show();
	var id = QueryRecord(JSON.stringify(record), QueryRecordCallback,0)
	prints("QueryRecord="+id);
	if(id<0){
		alert("查询录像失败！"+id);
	}
}

function QueryRecordCallback(id, info, userdata)
{
	var obj = JSON.parse(info);
	if(!obj || !obj["items"]){
		alert("查询录像失败！");
		return
	}

	$('#listobjdiv').accordion('select','录像查询');

	obj = obj["items"];
	for(var i=0; i<obj.length;i++){
		var time = obj[i]["begintime"]+"-"+obj[i]["endtime"];
		var tag = "<tr data-value='"+JSON.stringify(obj[i])+"'><td> <a name='recorditem' class='record-id' href='#'>" + time + "</a></td> <td> <a class='record-p'href='#'> 播放</a></td> <td> <a class='record-d'href='#'> 下载</a></td></tr>";
		$('#record-list').append(tag);
	}

	//alert("QueryRecordCallback("+id+","+info+","+userdata+")");
}
function getRecordPathbytr(tr)
{
	var timeinfo = tr.parentNode.parentNode.getAttribute("data-value");
	timeinfo = JSON.parse(timeinfo);
	if(g_loginfo.type == 4)
	{
		var record = {
			"type":g_loginfo.type+1,
			"user":g_loginfo.user,
			"passwd":g_loginfo.passwd,
			"severip": g_loginfo.severip, 
			"severid":g_loginfo.severid,
			"severport":g_loginfo.severport,
			"deviceID":timeinfo.path,
			"beginTime":timeinfo.begintime,
			"endTime":timeinfo.endtime,
			"vodType":tree_target_record.vodtype,
			"title":tree_target_record.name,
			"displayMode":GetdisplayMode(),
			"hwdecoder":gethwdecoder()
		}
		return record;
	}
	else
	{
		var avpath = timeinfo.path;
		var devid = "";
		var chnlid = "";
		var info = JSON.parse(timeinfo.path)
		if(info)
		{
			avpath = info.avpath;
			devid  = info.devid;
			chnlid = info.chnlid;
		}
		var record = {
			"type":g_loginfo.type+1,
			"user":g_loginfo.user,
			"passwd":g_loginfo.passwd,
			"ip":g_loginfo.ip, 
			"port":g_loginfo.port,
			"path":avpath,
			"devid":devid,
			"chnlid":chnlid,
			"beginTime":timeinfo.begintime,
			"endTime":timeinfo.endtime,
			"storageaddr":timeinfo.storageaddr?timeinfo.storageaddr:"",
			"vodType":tree_target_record.vodtype,
			"title":tree_target_record.name,
			"displayMode":GetdisplayMode(),
			"hwdecoder":gethwdecoder()
		};
		return record;
	}
	
}



function btn_query_playclick()
{
	if(!tree_target_record)
		return;
	var record = getqueryrecordpath();
	record["displayMode"] = GetdisplayMode();
	record["hwdecoder"] = gethwdecoder();
	var index = GetUsefulIndex();
	playstreamEx(index, record);
}
function btn_query_download_click()
{
	if(!tree_target_record)
		return;
	record_download(getqueryrecordpath(),0);
}

////////////////列举通道树/////////////////////////////

function listobjexcallback(id,result, info, userdata)
{
	//prints("listobjexcallback("+id+","+info+","+userdata+")");
	
	   //整理数据结构
	   if (result == 0)
	   {
			if (info==null||info=="") {
				alert("listobjex失败！");
			}else{
				var data = JSON.parse(info);
				for (var i = 0; i < data.length; i++) {
					if (data[i].objtype == 0x0001 ) 
					{
						//组织结构
						var objinfo = data[i].objinfo;
						for(var j = 0; j < objinfo.length; j++)
						{
							var info = JSON.parse(objinfo[j]);
							if(info.name == g_loginfo.ip)
							{
								g_servertitle = info.title;	
								break;
							}
						}
					}else if (data[i].objtype == 0x0010 && g_listcameraID == id)
					{
						//摄像机
						var root = createZtree(g_servertitle,data[i].objinfo);
						$.fn.zTree.init($("#tvwCamera") ,setting, root);
						$('#listobjdiv').accordion('select','列表');  	
					}
				}
			}

			if(userdata == 0x0001) {
	   	//列举通道
				var param = JSON.parse(getLogininfo());
				//param.usergroup = $('#chk_usergroup').attr('checked');
				param.usergroup =  false;//$('#chk_usergroup').attr('checked');
				param = JSON.stringify(param);
				ret = ListObjectsEx(param, 0x0010,"", listobjexcallback,0x0010); 
				ret = JSON.parse(ret);
				if(ret && ret["error"]==0)
				{
					g_listcameraID = ret["id"];
					g_loginfo = JSON.parse(param);
					$.fn.zTree.init($("#tvwCamera") ,setting, {});
					tree_target = null;
					tree_target_record = null;
					$('#record-list').empty();
				}
				else {
					alert("ListObjectsEx(0x0010) = "+ret);
				}
		   }
	   }else {
		   alert("listobjex err="+result);
	   }
}




function btn_listobject_click(param)
{
	var id = ListObjects(param, listobjcallback,0);
	if(id > 0){
		g_loginfo = JSON.parse(param);
		//$.fn.zTree.init($("#tvwCamera") ,setting, {});
		//tree_target = null;
		//tree_target_record = null;
		//$('#record-list').empty();
	}
	else
		alert("摄像机列表获取失败！"+id);
	prints("ListObjects = "+id);
}

function btn_updateobject_click()
{
	var param = getLogininfo();
	var id = UpdateObjects(param, listobjcallback,0);
	if(id > 0){
		g_loginfo = JSON.parse(param);
		$.fn.zTree.init($("#tvwCamera") ,setting, {});
		tree_target = null;
		tree_target_record = null;
		$('#record-list').empty();
	}
	else
		alert("UpdateObjects = "+id);
}

function getservertype()
{
	var chkObjs = document.getElementsByName("servertype");
	for(var i=0;i<chkObjs.length;i++){
		if(chkObjs[i].checked){
			return parseInt($(chkObjs[i]).attr('value'));
		}
	}
}

function getLogininfo()
{
	var servertype = getservertype();
	var type  = 1;
	if(servertype == 2)
		type = 4; //sip
	else if(servertype == 1)
		type = 8; //PVG+
	else if(servertype == 3)
		type = 14; //pau
	else 
		type = 1;//PVG

	if(type == 4)
	{
		var info = {
				"type":type,
				"user":$('#username_login').attr('value'),
				"passwd":$('#password_login').attr('value'),
				"severip": $('#pvgip_login').attr('value'), 
				"severid":$('#pvgid_login').attr('value'),
				"severport":parseInt($('#port_login').attr('value')),
		
		}
		return JSON.stringify(info);
	}
	var info ={
		"type":type,
		"user":$('#username_login').attr('value'),
		"passwd":$('#password_login').attr('value'),
		"ip": $('#pvgip_login').attr('value'), 
		"port":parseInt($('#port_login').attr('value'))
	}
	return JSON.stringify(info);
}

function listobjcallback(id, info, userdata)
{
	//prints("listobjcallback("+id+","+info+","+userdata+")");
	g_camerainfo = info;
	//$("#listdd").html(g_camerainfo);
	refreshcamera();
}

function refreshcamera()
{
	if(g_camerainfo==null||g_camerainfo==""||g_camerainfo=="ERROR"){
		alert("摄像机列表获取失败！");
		return;
	}
	var tempjson = JSON.parse(g_camerainfo)
	if(tempjson==null){
		alert("摄像机列表获取失败！");
		return;
	}
	//var zTreeNodes= gettree(tempjson);
	//adjustjsontree(zTreeNodes)
	//$.fn.zTree.init($("#tvwCamera") ,setting, zTreeNodes);

	//$('#listobjdiv').accordion('select','列表');  
	
}


function Getistrack()
{
	var istrack = false;
	if($('#chk_track').attr('checked')){
		istrack = true;
	}
	return istrack;
}


function tvwCamera_dblclick(treeNode)
{
	if(g_loginfo==null)
		return;
	var stream = {};
	if(g_loginfo.type == 4)
	{
		stream = {
			"type":g_loginfo.type,
			"user":g_loginfo.user,
			"passwd":g_loginfo.passwd,
			"severip": g_loginfo.severip, 
			"severid":g_loginfo.severid,
			"severport":g_loginfo.severport,
			"deviceID":treeNode.data,
			"title":treeNode.name, 
			"displayMode":GetdisplayMode(),
			"hwdecoder":gethwdecoder()
		};
	}
	else
	{
		stream = {
			"type":g_loginfo.type,
			"user":g_loginfo.user,
			"passwd":g_loginfo.passwd,
			"ip":g_loginfo.ip, 
			"port":g_loginfo.port,
			"path":treeNode.data,
			"title":treeNode.name,
			"devid":treeNode.devid,
			"chnlid":treeNode.chnlid,
			"istrack":Getistrack(), //false
			"initinfo":GetfolderPath()+"/trackinit/initinfo.json", //D:/Program Files (x86)/NetPosa/NP Video Player Plugins/demo/np_vpp_web +
			//"initpos":GetfolderPath()+"/trackinit/initpos.json",
			//"initinfo":"D:/SVN/test/bin/testImg/initialization.txt",
			//"initpos":"D:/SVN/test/bin/testImg/initialization.txt",
			"displayMode":GetdisplayMode(),//0
			"hwdecoder":gethwdecoder() //0
		};
	}
	console.log(stream);
	var index =0;
	//console.log(index);
	playstreamEx(index, stream);
	//treeNode.icon = openimg;
	//var treeObj = $.fn.zTree.getZTreeObj("tvwCamera");
	//treeObj.updateNode(treeNode);
	//win_hwnd_list[index].treenode = treeNode;
	//var div = document.getElementById("listobjdiv");
}
function updatestreamspeed()
{
	var myChart = echarts.init(document.getElementById('div_streamspeed'));
	var timeTicket = null; 
	var data = []; 
	var index = [];
	var data2 = [];
	for (var len=0;len<50;len++) {
		index.push(len);
		data.push(0);
		data2.push(0);
	}
	var option = {
		animation:false,
		title:{
			text: 'max:0 avg:0 cur:0 kbps',
			textStyle:{
				fontSize: 12,
				fontWeight: 'normal'
			},
			x:'center',
			y:'bottom' 
		},
		grid:{
			x:50,
			y:10,
			x2:10,
			y2:40
		},
		xAxis: {
			type: 'category',
			boundaryGap: false,
			data: index,
		},
		yAxis:{
			type: 'value',
			boundaryGap: [0, '10%']
		},
		series:{
			name:'流量',
			type:'bar',
			data:data
		}
	};
	if(timeTicket){
		clearInterval(timeTicket);
	}
	timeTicket = setInterval(function (){
		var speed = getstreamspeed();
		option.series.data.push(speed)
		option.series.data.shift(); 
		var navg = avg(option.series.data); 
		option.title.text = 'max:'+max(option.series.data)+' avg:'+navg+' cur:'+speed+' kbps'
		myChart.setOption(option);
	}, 1000);
}

function getstreamspeed()
{
	var dspeed = 0;
	for(var index=0;index<win_hwnd_list.length;index++){
		if(win_hwnd_list[index].type>0){//非本地文件
			var speed = GetTransferSpeed(index);
			if(speed!="ERROR"){
				dspeed += parseInt(speed.replace(/\D/g, ""));
			}
		}
	}
	return dspeed;
}

function btn_openrealdraw_click()
{
	var index = parseInt($('#txt_realdraw_pos').attr('value'));
	var type = parseInt($('#txt_realdraw_type').attr('value'));
	return OpenRealDraw(index,type);
}
function btn_closerealdraw_click()
{
	var index = parseInt($('#txt_realdraw_pos').attr('value'));
	return CloseRealDraw(index);
}
function btn_realdrawObject_click()
{
	var index = parseInt($('#txt_realdraw_pos').attr('value'));
	return RealDrawObject(index);
}
function btn_removerealdrawObject_click()
{
	return RemoveRealDrawObject(selectrealdrawObjectPos,selectrealdrawObjectID);
}


function btn_ssnpvg_play_click()
{
	var stream = {
		"type":16,//pvgsn
		"user":$('#txt_ssnpvguser').attr('value'),
		"passwd":$('#txt_ssnpvgpassword').attr('value'),
		"ip": $('#txt_ssnpvgip').attr('value'), 
		"port":parseInt($('#txt_ssnpvgport').attr('value')),
		"path":$('#txt_ssnpvgpath').attr('value'),
		"snserverip":$('#txt_ssnip').attr('value'),
		"snserverport":parseInt($('#txt_ssnport').attr('value'))
	}
	var index = GetUsefulIndex();
	playstreamEx(index, stream);
}
function btn_ssnrtsp_play_click()
{
	var stream = {
		"type":17,//pvgsn
		"url":$('#txt_ssnrtsppath').attr('value'),
		"snserverip":$('#txt_ssnip').attr('value'),
		"snserverport":parseInt($('#txt_ssnport').attr('value'))
	}
	var index = GetUsefulIndex();
	playstreamEx(index, stream);
}